Pull large .js file into its own chunk with webpack

时间:2017-04-24 17:36:35

标签: webpack create-react-app

I'm writing a single-page app which I've created with create-react-app. It loads a very large word list file, scrabble-dictionary.js, that never changes. Compiling was taking forever every time I made a change to some other part of my code, so I want to pull that large file into its own compiled chunk.

As far as I can tell, there's no way to tell create-react-app to do this without running npm run eject, which pulls all the config files out so you can edit them.

Now I have a webpack.config.dev.js file. I've used webpack before, but it's been a couple years, so I'm fairly rusty. I've tried adding multiple entry points: one for index.js, which is what create-react-app added by default, and one for my word list file. Oddly, webpack generates the two identical files which are the entire app including both the code for index.js and the word list file.

By default (immediately after running npm run eject), the webpack config file looks like this:

// ...
module.exports = {
  devtool: 'cheap-module-source-map',
  entry: [
    require.resolve('react-dev-utils/webpackHotDevClient'),
    require.resolve('./polyfills'),
    paths.appIndexJs
  ],
  output: {
    // Next line is not used in dev but WebpackDevServer crashes without it:
    path: paths.appBuild,
    pathinfo: true,
    filename: 'static/js/bundle.js',
    publicPath: publicPath
  },
  // ...
};

I've augmented my paths.js file to include:

module.exports = {
  // ...
  // custom entry points
  appWordsJs: resolveApp('src/scrabble-dictionary.js'),
};

Then I changed webpack.config.dev.js to

// ...
module.exports = {
  // ...
  entry: {
    webpackHotDevClient: [require.resolve('react-dev-utils/webpackHotDevClient')],
    vendor: [require.resolve('./polyfills')],
    main: [
        // Finally, this is your app's code:
        paths.appIndexJs
      ],

    dictionary: [paths.appWordsJs],
  },
  output: {
    // Next line is not used in dev but WebpackDevServer crashes without it:
    path: paths.appBuild,
    pathinfo: true,
    filename: 'static/js/[name].js',
    publicPath: publicPath,
    plugins: [ new webpack.optimize.CommonsChunkPlugin('dictionary', paths.appWordsJs)]
  },
// ...

It doesn't seem to make a difference if I include the plugins or not.

I also tried setting dictionary to [require.resolve(__dirname + '/../src/scrabble-dictionary.js')] with the same result.

0 个答案:

没有答案