Use different output.libraryTarget for a Web Worker
Asked Answered
S

1

6

I have this Webpack configuration:

{
  output: {
    libraryTarget: "system",
    ...
  },
  ...
}

I'm trying to use a Web Worker. I'm using the standard Webpack 5 syntax:

new Worker(new URL('./MyWorker', import.meta.url));

Now Webpack outputs the Web Worker as a System.js module. How can I change it to something different, like ES module, without affecting the main bundle?

Stringency answered 26/11, 2021 at 12:37 Comment(0)
T
0

You can use chunkFormat to specify what the chunk formats are, workers are by default array-push, https://webpack.js.org/configuration/output/#outputchunkformat.

You can also create multiple configs with different targets for different entries.

const config = {
  //
}

module.exports = (env) => {
  if (env.module) {
    config.entry = //path/to/index
    config.output.libraryTarget = 'module'
  } else {
    config.entry = //path/to/worker
    config.output.libraryTarget = 'umd'
  }

  return config
}

Then you can separately compile your web workers or chunks different from others. You can also use chunkFileName: () => along with that.

If you want to compile it in a single run, without having to run it twice using different configs, you can also manually invoke the webpack compiler with both configs.

import {Compiler} from 'webpack'
// or import webpack from 'webpack'

compiler.run(config)
compiler.run(config2)

Then you can run both of them at the same time and compile everything.

Another possible option is enabledChunkLoadingTypes, https://webpack.js.org/configuration/output/#outputenabledchunkloadingtypes, which will allow you to specify the available loading types for chunks which webpack will automatically use based on the entry function. I've never used that myself so I don't know if that'll work but it's something you can try.

Townshend answered 29/11, 2021 at 0:29 Comment(1)
chunkFormat and enabledChunkLoadingTypes didn't work for me. As for multiple configurations, I'm already using this workaround, but I was hoping for a simpler solution.Birmingham

© 2022 - 2024 — McMap. All rights reserved.