Skip to content

Add type option to Worker constructor

This PR adds a type option to the Worker constructor, inspired from WorkerType in HTML spec, and support for data: URLs.

  • When eval is true OR filename is a data: URL object, the type option explicitly tells Node.js what kind of JS to expect (ESM or CJS).
  • Otherwise, the option is ignored and the usual file extension rules is used.
// use ESM loader to load the worker.js file
new Worker('./worker.js', { type: 'module' });

// eval ESM
new Worker('export default import.meta.url', { eval: true, type: 'module' });

// data: URL
new Worker(
  new URL('data:text/javascript,export default import.meta.url'),
  { type: 'module' }
);

Note: new Worker('./worker.cjs', {type: 'module'}) would load worker.cjs as ES module and new Worker('./worker.mjs', {type: 'classic'}) would load worker.mjs as CJS. I don't expect anyone to have a use-case for this edge-case, but I wanted to clarify it's a possibility with this PR's implementation. This has been reverted based on this PR's comments.

I had to tweak some internal functions, I have put those changes in separate commits to make reviewing them easier.

Fixes: #30682

Checklist
  • make -j4 test (UNIX), or vcbuild test (Windows) passes
  • tests and/or benchmarks are included
  • documentation is changed or added
  • commit message follows commit guidelines

Merge request reports

Loading