我在开发PWA时遇到了一个问题。我使用webpack,并看到了几个框架可以生成service worker。但是我想自己创建它,以便理解其工作原理。然而,我无法将我在src文件中创建的service worker与webpack联系起来。有人知道怎么做吗?谢谢。
我在开发PWA时遇到了一个问题。我使用webpack,并看到了几个框架可以生成service worker。但是我想自己创建它,以便理解其工作原理。然而,我无法将我在src文件中创建的service worker与webpack联系起来。有人知道怎么做吗?谢谢。
sw.js
(服务工作者),您需要按照这里描述的三个步骤进行操作。
Add the plugin to your webpack config, Do npm i -D serviceworker-webpack-plugin
. And add this code to your webpack.config.js
import ServiceWorkerWebpackPlugin from 'serviceworker-webpack-plugin';
...
plugins: [
new ServiceWorkerWebpackPlugin({
entry: path.join(__dirname, 'src/sw.js'),
}),
],
Register the service worker in your main JS thread. Just add this code block somwhere at the begining of your script.
import runtime from 'serviceworker-webpack-plugin/lib/runtime';
if ('serviceWorker' in navigator) {
const registration = runtime.register();
}
Write your own sw.js. Create file sw.js
inside src
floder, and just paste code from plugin example. File name and pass are configurable with plugin options. Important: inside sw.js
you have access to global.serviceWorkerOption.assets
. So you can manage all your compiled files (even if you don't now their final names). If you want to create sw.js from scratch look at google docs for more info.
...
const { assets } = global.serviceWorkerOption;
...
请查看这个插件https://github.com/oliviertassinari/serviceworker-webpack-plugin
它应该能解决你的问题。