Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 565
João Melo Avatar asked Oct 27 '25 14:10

João Melo


1 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';
  },
},
like image 167
Dolphin_Wood Avatar answered Oct 30 '25 15:10

Dolphin_Wood



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!