Webpack - Service Worker

3

我在开发PWA时遇到了一个问题。我使用webpack,并看到了几个框架可以生成service worker。但是我想自己创建它,以便理解其工作原理。然而,我无法将我在src文件中创建的service worker与webpack联系起来。有人知道怎么做吗?谢谢。


2
你看过这个吗?https://github.com/oliviertassinari/serviceworker-webpack-plugin - Karen Grigoryan
好的。已经添加为答案,您可以接受它,谢谢。 - Karen Grigoryan
2个回答

4
Karen说得对!这是您问题的合适插件
我只想在这里添加一点描述。
要正确注册您的sw.js(服务工作者),您需要按照这里描述的三个步骤进行操作。
  1. 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'),
        }),
    ],
    
  2. 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();
    }
    
  3. 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;
    ...
    

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接