创建React App中的工作箱而无需弹出

时间:2018-07-26 07:45:57

标签: javascript reactjs create-react-app workbox

我正在尝试在CRA中配置Workbox而不弹出。有人成功了吗?

2 个答案:

答案 0 :(得分:6)

经过数小时的尝试和错误,我成功地在CRA中安装了工作箱。这是我的做法:

首先,yarn add -D workbox-build

接下来,使用以下命令在根文件夹中创建一个名为build-sw.js的文件:

const fs = require('fs-extra');
const pathmodule = require('path');
const workbox = require('workbox-build');

function build() {
  const cwd = process.cwd();
  const pkgPath = `${cwd}/node_modules/workbox-sw/package.json`;
  const pkg = require(pkgPath);
  const readPath = `${cwd}/node_modules/workbox-sw/${pkg.main}`;
  let data = fs.readFileSync(readPath, 'utf8');
  let path = `${cwd}/build/workbox-sw.js`;
  console.log(`Writing ${path}.`);
  fs.writeFileSync(path, data, 'utf8');
  data = fs.readFileSync(`${readPath}.map`, 'utf8');
  path = `${cwd}/build/${pathmodule.basename(pkg.main)}.map`;
  console.log(`Writing ${path}.`);
  fs.writeFileSync(path, data, 'utf8');

  workbox
    .injectManifest({
      globDirectory: 'build',
      globPatterns: ['**/*.{html,js,css,png,jpg,json}'],
      globIgnores: ['sw-default.js', 'service-worker.js', 'workbox-sw.js'],
      swSrc: './src/sw-template.js',
      swDest: 'build/sw-default.js'
    })
    .then(_ => {
      console.log('Service worker generated.');
    });
}

try {
  build();
} catch (e) {
  console.log(e);
}

然后,在src/sw-template.js中使用以下命令创建文件: (请记住,必须在此文件中放置自己的缓存策略。有关详细信息,请参见Docs

workbox.setConfig({
  debug: true
});

workbox.core.setLogLevel(workbox.core.LOG_LEVELS.debug);

workbox.precaching.precacheAndRoute([]);

workbox.skipWaiting();
workbox.clientsClaim();

workbox.routing.registerRoute('/', workbox.strategies.networkFirst());

最后,在src/registerServiceWorker.js中进行更改:

-      const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
+      const swUrl = `${process.env.PUBLIC_URL}/sw-default.js`;

然后在package.json中进行更改:

-      "build": "react-scripts build && sw-precache --config=sw-precache-config.js'",
+      "build": "react-scripts build && yarn sw",
+      "sw": "node build-sw.js"

希望有帮助!

答案 1 :(得分:4)

通过合并this PR,Create React App 2现在支持开箱即用的工作箱,因为它现在在内部使用 workbox-webpack-plugins

看看官方文档以了解更多信息:https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app