generate-register-sw-plugin
v1.0.4
Published
a plugin to generate a code snippet for registe service worker based on the template, inline or outreach to html
Maintainers
Readme
使用方法
npm i generate-register-sw-plugin
测试例子
npm run inject:example
npm run example
跑完之后可以在 dist 目录下找到对应的 service-worker.js swRegister.js precacheManifest.js 等文件
字段说明
swFilePath:service-worker的规则文件路径,默认优先使用workboxGenrateSWOption配置中的swDest字段, 不存在上述字段的时候再使用swFilePath的值, 该字段会替换模版中的{{swFilePath}}字符串,具体请看build/swTpl.js文件swRegisterFileName:生成的注册service-worker的js文件路径,没有默认使用js/swRegister.js路径tplPath:生成的注册service-worker的js文件的参照模版路径,没有即将使用默认build/swTpl.js文件inject:是否注册service-worker的代码直接插入到html的最后面,默认false,false将会以外链的方式插入到最后面,使用该功能需要把该插件放到html-webpack-plugin后面,否则会找不到html文件tplData:模版所需要的字段,{{env}}会被替换成env值的字符串,具体请看build/swTpl.js文件injectHtmlPath: 存在该字段的时候,会在这个html下注入js代码, 并且忽略html-webpack-plugin生成的htmlworkboxGenrateSWOption: 支持workbox-webpack-plugin的GenerateSW插件配置(对该配置项完全透传给workbox-webpack-plugin), 详细见: https://developers.google.com/web/tools/workbox/modules/workbox-webpack-plugin#full_generatesw_config, 使用该配置有些坑, 比如在runtimeCaching中不配置cacheName就无法使用expiration,precacheManifestFilename如果不包含[manifestHash]也跑不起来, 这是workbox-webpack-plugin本身存在的问题workboxInjectManifestOption: 支持workbox-webpack-plugin的预加载InjectManifest插件,详细配置见 https://developers.google.com/web/tools/workbox/modules/workbox-webpack-plugin#injectmanifest_plugin_2
注意: 该插件最好配合 html-webpack-plugin 一起使用, 放在 html-webpack-plugin 插件后面, 会自动为所有生成的 html 文件插入注册的代码
new GenerateRegisterSWJS({
swFilePath: './service-worker.' + process.env.BUILD_ENV + '.js',
swRegisterFileName: 'js/swRegister.js',
tplPath: undefined,
inject: false,
injectHtmlPath: './example/index.html',
tplData: {
env: process.env.BUILD_ENV,
version: BUILD_VERSION,
isOpenPWA: process.env.BUILD_ENV === 'dev' ? true : true
},
workboxGenrateSWOption: object || false,
workboxInjectManifestOption: object || false
})
})