Serviceworker Chunk with CommonsChunkPlugin doesn't work, webpackJsonp is not defined

825 views Asked by At

I'm trying to create a serviceworker chunk (sw.js) with webpack2 using the CommonsChunkPlugin but when trying to register /sw.js as a serviceworker I get the error Uncaught ReferenceError: webpackJsonp is not defined.

Apparently webpackJsonp is for async loading of chunks and is messing up my serviceworker file. Is there anyway to remove async loading for the serviceworker chunk?

My webpack config:

{
  entry: {
    main: [
      'react-hot-loader/patch',
      `webpack-dev-server/client?http://${host}:${port}`,
      'webpack/hot/only-dev-server',
      './index.jsx',
    ],
    sw: './sw.js',
    vendor: [...],
  },
  output: {
    filename: '[name].js',
    path: resolve(__dirname, 'dist'),
    publicPath: '/',
  },
  resolve: { extensions: ['.js', '.jsx'] },
  performance: { hints: false },
  context: resolve(__dirname, 'src'),
  devtool: 'inline-source-map',

  devServer: {
    hot: true,
    host,
    port,
    contentBase: resolve(__dirname, 'dist'),
    publicPath: '/',
  },

  module: {
    rules: [
      {
        test: /\.jsx?$/,
        use: 'babel-loader',
        exclude: /node_modules/,
      },
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract('css-loader'),
      },
    ],
  },

  plugins: [
    new ExtractTextPlugin('main.css'),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(),
    new webpack.optimize.CommonsChunkPlugin({
      names: ['vendor', 'manifest'],
    }),
  ],
};
1

There are 1 answers

0
VISHAL DAGA On

If you extract only your webpack runtime code (which has webpackJsonp defined) into your manifest bundle and load it before all other script, it should work.

So, you would want to rewrite as

plugins: [
   ...
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor'
    }),
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
      chunks: 'vendor',
      minChunks: Infinity
    }),
  ],