考虑以下情况:
我的快递服务器为我的单页应用程序的“/”路由动态生成HTML。
当用户离线时,我想重新提供与服务工作者navigateFallback相同的生成HTML。
我在我的webpack配置中使用https://www.npmjs.com/package/sw-precache-webpack-plugin。
如果我通过html-webpack-plugin生成index.html,并将index.html设置为我的navigateFallback文件,那么生成的文件将由服务工作者正确提供。
但是,我看不出有什么方法可以使动态呈现的索引html(实时服务器为“/”路径返回的内容)被缓存并用作离线html。
答案 0 :(得分:4)
使用Service Worker Precache的dynamicUrlToDependencies
选项来缓存路由URL及其依赖项。然后将navigateFallback
设置为'/'
,将navigateFallbackWhitelist
设置为与子链接逻辑匹配的正则表达式。
采取以下配置:(在您的webpack配置上添加const glob = require('glob')
)
new SWPrecacheWebpackPlugin({
cacheId: 'my-project',
filename: 'offline.js',
maximumFileSizeToCacheInBytes: 4194304,
dynamicUrlToDependencies: {
'/': [
...glob.sync(`[name].js`),
...glob.sync(`[name].css`)
]
},
navigateFallback: '/',
navigateFallbackWhitelist: [/^\/page\//],
staticFileGlobsIgnorePatterns: [/\.map$/],
minify: false, //set to "true" when going on production
runtimeCaching: [{
urlPattern: /^http:\/\/localhost:2000\/api/,
// Use network first and cache as a fallback
handler: 'networkFirst'
}],
})
答案 1 :(得分:0)
应支持该用例。我有example of something similar使用底层sw-precache
库,我相信在使用Webpack包装器时语法应该是等效的。
在这种情况下,/shell
是用于动态生成来自服务器的内容的网址,构成App Shell,但听起来您的用例类似,/
代替/shell
。
{
// Define the dependencies for the server-rendered /shell URL,
// so that it's kept up to date.
dynamicUrlToDependencies: {
'/shell': [
...glob.sync(`${BUILD_DIR}/rev/js/**/*.js`),
...glob.sync(`${BUILD_DIR}/rev/styles/all*.css`),
`${SRC_DIR}/views/index.handlebars`
]
},
// Brute force server worker routing:
// Tell the service worker to use /shell for all navigations.
// E.g. A request for /guides/12345 will be fulfilled with /shell
navigateFallback: '/shell',
// Other config goes here...
}