如何使用create-react-app配置服务工作者

Lil*_*Sap 15 reactjs webpack service-worker progressive-web-apps

我正在使用create-react-app实用程序创建一个ReactJS应用程序.如何配置它以使用包含服务工作者的文件?

编辑:从Javascript方面对我来说很清楚,在我的index.js中添加注册:

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('./service_workers/sw.js')
  .then(function(registration) {
    // Registration was successful...
  }).catch(function(err) {
    // registration failed ...
  });
}
Run Code Online (Sandbox Code Playgroud)

然后我的服务工作文件中的配置(对我来说是在service_wokers/sw.js):

self.addEventListener('install', function(event) {//my code here...});
self.addEventListener('activate', function(event) {//my code here...});
self.addEventListener('fetch', function(event) {//my code here...});
Run Code Online (Sandbox Code Playgroud)

当我运行此控制台时,控制台显示:ServiceWorker注册失败:DOMException:无法注册ServiceWorker:获取脚本时收到错误的HTTP响应代码(404).

该文件不存在,因为我没有配置Webpack来执行此操作.所以我试图用ouput复制sw.js文件:

test: 
     /\.(js)$/,
     loader: "file?name=[path][name].[ext]&context=./service_workers",
     include: '/service_worker'
Run Code Online (Sandbox Code Playgroud)

我认为没有必要说我对Webpack完全不熟悉.

Aye*_*ndu 9

对于仍在为此苦苦挣扎的人。请参考https://create-react-app.dev/docs/making-a-progressive-web-app

在此处输入图片说明

服务工作者在 CRA 中配置,并将为您处理缓存!你只需要改变:-

serviceWorker.unregister();
Run Code Online (Sandbox Code Playgroud)

serviceWorker.register();
Run Code Online (Sandbox Code Playgroud)

在您的src/index.js文件中;

此外,服务工作者仅在生产模式下工作,因此请确保在为服务工作者测试您的应用程序之前构建您的应用程序并在本地提供它。

npm i http-server -D
Run Code Online (Sandbox Code Playgroud)

然后将此添加到package.json, 在您的脚本中。

"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "start-sw": "http-server ./build"
}
Run Code Online (Sandbox Code Playgroud)

现在运行:-

npm run build && npm run start-sw
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你!


Moh*_*ban 8

首先,你必须在package.json中做一些更改:

package.json中的更改:

{
  "name": "create-react-pwa",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "react-scripts": "0.7.0",
    "sw-precache": "^4.2.2"
  },
  "dependencies": {
    "react": "^15.4.0",
    "react-dom": "^15.4.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build && sw-precache --config=sw-precache-config.js",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}
Run Code Online (Sandbox Code Playgroud)

然后在项目的根文件夹中创建一个js文件"sw-precache-confi.js":

SW-预缓存-config.js:

 module.exports = {
    stripPrefix: 'build/',
    staticFileGlobs: [
      'build/*.html',
      'build/manifest.json',
      'build/static/**/!(*map*)'
    ],
    dontCacheBustUrlsMatching: /\.\w{8}\./,
    swFilePath: 'build/service-worker.js'
};
Run Code Online (Sandbox Code Playgroud)

index.html中的更改,在index.html中添加服务工作者:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
    <!--
      Notice the use of %PUBLIC_URL% in the tag above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.
      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
  </head>
  <body>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.
      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.
      To begin the development, run `npm start`.
      To create a production bundle, use `npm run build`.
    -->
    <script>
      if ('serviceWorker' in navigator) {
        window.addEventListener('load', function() {
          navigator.serviceWorker.register('/service-worker.js');
        });
      }
    </script>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

完成所有事情后,npm install在项目的根目录运行npm start.

进一步阅读:https://github.com/jeffposnick/create-react-pwa#what-additional-changes-might-be-needed

  • 如果你解释为什么这些步骤是必要的而不是盲目地遵循指示,那就太棒了. (10认同)

小智 6

我会推荐这个名为cra-append-sw 的库来向 CRA 添加自定义服务工作者。

关于如何使用它的大部分细节都在 npm 页面中,但简单地说你只需要安装这个库(npm i --save cra-append-sw)。

对您的 package.json 进行一些更改:

"start": "react-scripts start && cra-append-sw --mode dev ./public/custom-sw-import.js",
"build": "react-scripts build && cra-append-sw --skip-compile ./public/custom-sw-import.js" 
Run Code Online (Sandbox Code Playgroud)

最后在您的公共文件夹中创建一个名为 custom-sw-import.js 的文件,您在那里编写的所有 service worker 代码将简单地附加到 cra 的 service worker。

我可以验证这是否有效,因为我应用了相同的原则来制作我的网站www.futurist-invenzium.com,该网站提供了 PWA 提供的所有功能的演示。

如果您想要更深入的答案,我还发现这篇博文很有帮助:https : //medium.freecodecamp.org/how-to-build-a-pwa-with-create-react-app-and-custom-service-工人-376bd1fdc6d3