A web worker script can be imported using new Worker()
and new SharedWorker()
(inspired by vite).
npm i -D @farmfe/plugin-worker
Create a farm.config.js
configuration file and import the plugin:
import { defineConfig } from '@farmfe/core';
import worker from '@farmfe/plugin-worker';
export default defineConfig({
plugins: [
worker(),
],
});
A Web Worker can be imported using new Worker()
and new SharedWorker()
. This syntax is closer to the standard compared to the worker suffix and is the recommended way to create workers.
const worker = new Worker(new URL('./worker.js', import.meta.url));
The Worker constructor accepts options that can be used to create a "module" worker:
const worker = new Worker(new URL('./worker.js', import.meta.url), {
type: 'module',
});
You can directly import a web worker script by adding the ?worker
or ?sharedworker
query parameter to the import request. The default export will be a custom worker constructor:
import MyWorker from './worker?worker';
const worker = new MyWorker();
This worker script can also use ESM import statements instead of importScripts()
. Note: During development, this relies on native browser support, but in production builds, it will be compiled away.
By default, the worker script will compile into a separate chunk in production builds. If you want to inline the worker as a base64 string, please add the inline
query parameter:
import MyWorker from './worker?worker&inline'
If you want to read the worker as a URL, add the url
query:
import MyWorker from './worker?worker&url'