Add worker plugin to plugin esbuild

Summary:
## Context
https://fb.workplace.com/groups/flippersupport/posts/1722856878194963

## Changes
* Add a worker plugin that takes modules suffixed with `?worker`, bundles them, treats them as web workers, and returns a function as a default export that instanitates a new worker

Reviewed By: antonk52

Differential Revision: D51059224

fbshipit-source-id: cef89486f7a2d5b8ce38354df4a5749271a6c41d
This commit is contained in:
Aria Fallah
2023-11-07 11:09:10 -08:00
committed by Facebook GitHub Bot
parent 39b1b37172
commit 3536ffe737

View File

@@ -28,6 +28,40 @@ const resolveFbStubsToFbPlugin: Plugin = {
},
};
const workerPlugin: Plugin = {
name: 'worker-plugin',
setup({onResolve, onLoad}) {
onResolve({filter: /\?worker$/}, (args) => {
return {
path: require.resolve(args.path.slice(0, -7), {
paths: [args.resolveDir],
}),
namespace: 'worker',
};
});
onLoad({filter: /.*/, namespace: 'worker'}, async (args) => {
// Bundle the worker file
const result = await build({
entryPoints: [args.path],
bundle: true,
write: false,
format: 'iife',
platform: 'browser',
});
const dataUri = `data:text/javascript;base64,${Buffer.from(
result.outputFiles[0].text,
).toString('base64')}`;
return {
contents: `export default function() { return new Worker("${dataUri}"); }`,
loader: 'js',
};
});
},
};
interface RunBuildConfig {
pluginDir: string;
entry: string;
@@ -73,7 +107,7 @@ async function runBuild({
],
sourcemap: dev ? 'inline' : 'external',
minify: !dev,
plugins: intern ? [resolveFbStubsToFbPlugin] : undefined,
plugins: [workerPlugin, ...(intern ? [resolveFbStubsToFbPlugin] : [])],
loader: {
'.ttf': 'dataurl',
},