web-dev-qa-db-fra.com

Comment configurer les opérateurs de service avec create-react-app

Je crée une application ReactJS avec l'utilitaire create-react-app. Comment puis-je le configurer pour utiliser un fichier qui contiendra un agent de service?

EDIT: Du côté du javascript est clair pour moi, ajoutez l'enregistrement dans mon index.js:

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

Ensuite, ma configuration dans mon fichier de service worker (qui pour moi est dans 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...});

Lorsque j'exécute cette opération, la console affiche:.

Le fichier n'est pas là car je ne configure pas Webpack pour le faire. J'essaie donc de copier le fichier sw.js avec la sortie avec:

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

Je pense qu'il n'est pas nécessaire de dire que je suis totalement nouveau pour Webpack.

10
LilSap

Tout d’abord, vous devez faire quelques changements dans package.json:

Changements dans 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"
  }
}

Créez ensuite un fichier js "sw-precache-confi.js" dans le dossier racine de votre projet:

sw-precache-config.js:

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

Modifications dans index.html, Ajouter un agent de service dans 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>

Après avoir tout fait, lancez npm install à la racine du projet, puis npm start.

Lectures supplémentaires: https://github.com/jeffposnick/create-react-pwa#what-additional-changes-might-be-needed

7
Mohammad shaban

Les opérateurs de service et les fonctionnalités hors ligne doivent maintenant être inclus dans les versions de create-react-app, voir ce pr

0
Will Farley

Je recommanderais cette bibliothèque appelée cra-append-sw pour ajouter des agents de service personnalisés à l'ARC. 

La plupart des détails sur son utilisation se trouvent dans la page npm, mais vous devez simplement installer la bibliothèque (npm i --save cra-append-sw). 

Apportez quelques modifications à votre 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" 

Et enfin, créez un fichier dans votre dossier public appelé custom-sw-import.js et tout le code de travailleur de service que vous y écrivez sera simplement ajouté au travailleur de service de cra.

Je peux vérifier que cela fonctionne puisque j'ai appliqué le même principe pour rendre mon site Web www.futurist-invenzium.com qui donne une démonstration de toutes les fonctionnalités fournies par PWA. 

J'ai également trouvé cet article de blog utile si vous voulez une réponse plus approfondie: https://medium.freecodecamp.org/how-to-build-a-pwa-with-create-react-app-and-custom- service-workers-376bd1fdc6d3

0
NatSerAchilles