在不弹出的情况下创建 React App 中的工作箱

Workbox in Create React App without eject

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

经过数小时的反复试验,我成功地在 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"

希望对您有所帮助!

this PR, Create React App 2 now support supports Workbox out of the box, since it now uses workbox-webpack-plugins内部合并。

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