How to set webpackChunkName for import() globally?

Viewed 3899

Since Webpack@3.0.0 we have this great feature which enables named chunk files:

import(
  /* webpackChunkName: "my-chunk-name" */
  /* webpackMode: "lazy-once" */
  'module'
);

However, I'm at the point where I have 40 imports like this and changing each one of them is kind of a hassle.

Is there any way to define webpackChunkName and webpackMode globally for all chunks?

I imagine something like this in webpack.config.js:

output: {
    filename:      'js/[name].js',
    chunkFilename: 'js/[filename].js' // so that import('module') creates module.js
    chunkMode:     'lazy-once' // so I can override default `lazy` option once and for all
}
1 Answers

Is there any way to define webpackChunkName and webpackMode globally for all chunks?

No, not as a built-in webpack configuration option. You might be able to use the SplitChunksPlugin and optimization.splitChunks.cacheGroups to appropriately name your dynamic imports, but that would only cover webpackChunkName.

You can use a loader to cover all magic comments. I've created magic-comments-loader for this purpose.

It relies on a RegExp to find the dynamic imports and replace to add the configured magic comments.

The loader can be used like this:

module: {
  rules: [
    {
      test: /\.js$/,
      exclude: /node_modules/,
      use: {
        loader: 'magic-comments-loader',
        options: {
          webpackChunkName: true,
          webpackMode: 'lazy',
          webpackIgnore: 'src/ignore/**/*.js',
          webpackPrefetch: [
            'src/prefetch/**/*.js',
            '!src/prefetch/not/*.js'
          ]
        }
      }
    }
  ]
}

You can use the loader options to further configure the magic comments, including overrides based on file paths. Check out the readme. Dynamic imports that already include comments of any kind are ignored.

NOTE: You need to be running a Node.js version that supports lookbehind assertions and named capture groups in regular expressions, so >= 10.3.0. See the support table at node.green.

Related