Workbox基本配置以获取资产/块

时间:2019-04-05 10:39:23

标签: reactjs webpack workbox

我一直在尝试在自定义的webpack项目中使用Workbox,但我觉得我有些迷茫。

我的目标是从服务工作者+其余的静态文件中获取js块。

当前我的webpack配置如下:

const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { clientPath, staticPath, currentWorkingDirectory, configPath } = require('../paths');
const Dotenv = require('dotenv-webpack');
const babelConf = require('../babelrc');
const TerserPlugin = require('terser-webpack-plugin');
const { GenerateSW } = require('workbox-webpack-plugin');
const { NODE_ENV, CYPRESS } = process.env;
const isDev = NODE_ENV === 'development';
const isProd = NODE_ENV === 'production';

const webpackConfig = {
  mode: NODE_ENV,
  devtool: isDev ? 'eval-source-map' : undefined,
  entry: {
    client: [
      'core-js/modules/es6.promise',
      'core-js/modules/es6.array.iterator',
      path.resolve(clientPath, 'client.tsx'),
    ],
  },
  output: {
    filename: '[name].bundle.js',
    chunkFilename: '[name].chunk.js',
    path: path.resolve(currentWorkingDirectory, 'build', 'client'),
    publicPath: '/assets/',
  },
  module: {
    rules: [
      {
        test: /\.(tsx?)|\.(jsx?)$/,
        exclude: /node_modules/,
        use: [
          {
            loader: 'babel-loader',
            options: {
              ...babelConf,
              cacheDirectory: isDev,
            },
          },
        ],
      },
      {
        test: /\.(jpg|png|svg)$/,
        use: {
          loader: 'url-loader',
          options: {
            limit: 25000,
          },
        },
      },
    ],
  },
  plugins: [
    new Dotenv({
      path: path.resolve(currentWorkingDirectory, '.env'),
      // machine env variables take precedence over those in .env
      systemvars: CYPRESS || isProd,
      silent: isProd,
    }),
    new webpack.DefinePlugin({
      __DEV__: isDev,
      __PROD__: isProd,
    }),
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, 'index.ejs'),
      chunks: ['client'],
    }),
    new TerserPlugin({...}),
    new GenerateSW({
      swDest: 'service-worker.js',
      clientsClaim: true,
      skipWaiting: true,
    }),
  ],
  profile: isDev,
  watch: isDev,
  watchOptions: {
    ignored: /node_modules/,
  },

  // Useful for optimizing de external dependencies. Uncomment to activate
  // new BundleAnalyzerPlugin(),
  resolve: {
    symlinks: isProd,
    extensions: ['.js', '.jsx', '.ts', '.tsx', '.json', '*'],
    mainFields: ['browser', 'module', 'main', 'types'],
  },
};

if (isDev) {
  webpackConfig.plugins.push(new webpack.HotModuleReplacementPlugin());
}
module.exports = webpackConfig;

我的index.ejs中有这个:

  if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
      navigator.serviceWorker.register('/assets/service-worker.js').then(registration
=> {
        console.log('SW registered: ', registration);
      }).catch((registrationError) => {
        console.log('SW registration failed: ', registrationError);
      });
    });   }

因此,每当我加载页面时,我都会用以下内容注册软件:

/**
 * Welcome to your Workbox-powered service worker!
 *
 * ...
 */

importScripts("https://storage.googleapis.com/workbox-cdn/releases/4.1.1/workbox-sw.js");

importScripts(
  "/assets/precache-manifest.ddd8b17ce0bc0a1ecf7bc6d1a5d8b832.js"
);

workbox.core.skipWaiting();

workbox.core.clientsClaim();

清单:

/**
 * The workboxSW.precacheAndRoute() method efficiently caches and responds to
 * requests for URLs in the manifest.
 * See ...
 */
self.__precacheManifest = [].concat(self.__precacheManifest || []);
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});

self.__precacheManifest = (self.__precacheManifest || []).concat([
  {
    "revision": "137741f4b7384bd4b2da",
    "url": "/assets/Onboarding.chunk.js"
  },
  {
    "revision": "16d41ee8945361f0d22e20185d323d4a",
    "url": "/assets/index.html"
  },
  {
    "revision": "0b06750859ab2667a078",
    "url": "/assets/vendors~Dashboard~Onboarding.chunk.js"
  },
  {
    "revision": "528d57fe189a244ba83d",
    "url": "/assets/OpenInsufficientFunds.chunk.js"
  },
  {
    "revision": "f0bc0ef109abd037e757",
    "url": "/assets/Dashboard~Onboarding.chunk.js"
  },
  {
    "revision": "2d41db393998fc587216",
    "url": "/assets/ErrorStep.chunk.js"
  },
  {
    "revision": "eb6aad1d525a6c54d376",
    "url": "/assets/ExpectedAmount.chunk.js"
  },
  {
    "revision": "e2b8e24b4ab5725b39cf",
    "url": "/assets/FailureInsufficientFunds.chunk.js"
  },
  {
    "revision": "d27900d0825c075f0b1f",
    "url": "/assets/KycAml.chunk.js"
  },
  {
    "revision": "06924db6ebc6ade0d162",
    "url": "/assets/Matured.chunk.js"
  },
  {
    "revision": "a52ea80876523dc37ffc",
    "url": "/assets/MemberConflict.chunk.js"
  },
  {
    "revision": "99198b15ba6366c9d3c2",
    "url": "/assets/MemberCreation.chunk.js"
  },
  {
    "revision": "14ff497a38508a3f82fe",
    "url": "/assets/NominatedAccount.chunk.js"
  },
  {
    "revision": "f22c4cc52ecc19eaf0a1",
    "url": "/assets/NonResidentRejection.chunk.js"
  },
  {
    "revision": "9c143a8a6a590c65854f",
    "url": "/assets/client.bundle.js"
  },
  {
    "revision": "3c5a20be89b88309f58f",
    "url": "/assets/UserDebugDashboard.chunk.js"
  },
  {
    "revision": "ca9267d1e0830e5c38c8",
    "url": "/assets/OpenSufficientFunds.chunk.js"
  },
  {
    "revision": "c94e7199ca5c48cf28d2",
    "url": "/assets/PeriodOpenNoFunds.chunk.js"
  },
  {
    "revision": "8d16616b001483751a73",
    "url": "/assets/ProductDescription.chunk.js"
  },
  {
    "revision": "35f6e282b5670e3fd86f",
    "url": "/assets/Reconciliation.chunk.js"
  },
  {
    "revision": "d9bad4a9afe5c23b8637",
    "url": "/assets/RedirectExternal.chunk.js"
  },
  {
    "revision": "99c168d65c76c530372c",
    "url": "/assets/SourceOfWealth.chunk.js"
  },
  {
    "revision": "13397b01a9296eaea18e",
    "url": "/assets/SuccessTermStarted.chunk.js"
  },
  {
    "revision": "dc3e1e7df9a37a8bc854",
    "url": "/assets/TaxResidency.chunk.js"
  },
  {
    "revision": "12604fb4dc1d454ea2b1",
    "url": "/assets/TermsAndConditions.chunk.js"
  },
  {
    "revision": "620ea69cd4b223dab23e",
    "url": "/assets/Dashboard.chunk.js"
  },
  {
    "revision": "89f94688e54bc9dae380",
    "url": "/assets/ContactPreferences.chunk.js"
  },
  {
    "revision": "21fb9840719c2fe31c52",
    "url": "/assets/AddressCreation.chunk.js"
  }
]);

所以我期望当我将React.lazy与dinamic导入一起使用时,我得到的资产来自服务工作者。但这不是。

在Chrome无痕模式下,我在控制台中收到以下消息:

console chrome

当我单击加载另一个块的按钮时,在网络选项卡中得到了这个消息:

network tab

这是不正确的,因为它应该对所有js文件的GET说“从磁盘”,不是吗?或者我缺少什么?

谢谢:)

0 个答案:

没有答案