how to change the output format of web worker files in webpack 5

Viewed 439

My project js files are bundled with Webpack 5 into a subfolder inside the dist output directory. Here is the config:

// webpack.config.js
output: {
      path: PATHS.CLIENT_DIST,
      publicPath: '/',
      filename: env.prod
        ? 'bundle/[name].[contenthash].bundle.js'
        : 'bundle/[name].bundle.js'
    },

And here are the bundle artifacts:

bundle

Please take notice of the js file highlighted in red starting with 323. The file is stubborn outside the bundle subfolder.

The file is a web worker created following the Webpack 5 docs, like this:

// some-file-inside-the-project.js
const workerUrl = new URL('pdfjs-dist/build/pdf.worker.js', import.meta.url);
pdfjsLib.GlobalWorkerOptions.workerPort = new Worker(workerUrl);

I'm asking for help on how to make this parsed output follow the same patterns as the other js files in the project and be put inside the bundle subfolder instead of the dist root.

The Webpack 5 docs offer no instructions (that I found) on how to control web workers output. I tried output.chunkFilename also with no effect.

2 Answers

Not sure if this is the best practice, but I think you can use the magic comment to do this:

const workerUrl = new URL(
  /* webpackChunkName: 'pdf.worker' */
  'pdfjs-dist/build/pdf.worker.js', 
  import.meta.url,
);

then in your webpack configs:

output: {
  chunkFilename(pathData) {
    const outDir = pathData.chunk.name === 'pdf.worker' ? 'worker/' : '';
    return outDir + '[name].[contenthash].bundle.js';
  },
},

Webpack 5 introduced Asset module using which I was able to control the output directory of the web worker bundle.

Check the below webpack configuration where I have used the /\.worker.js$/ pattern to identify all the worker scripts and using generator.filename I could control the output directory of the worker specific bundles.

module.exports = {
    entry: {...},
    module: {
        rules: [
            {
                test: /\.worker.js$/,
                exclude: /(node_modules)/,
                type: "asset/resource",
                generator: {
                    filename: "bundle/workers/[hash][ext][query]",
                },
            },
        ],
    },
}
Related