From 3536ffe73706b2d4907bdad930c99b0ad77195ba Mon Sep 17 00:00:00 2001 From: Aria Fallah Date: Tue, 7 Nov 2023 11:09:10 -0800 Subject: [PATCH] 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 --- desktop/pkg-lib/src/runBuild.tsx | 36 +++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/desktop/pkg-lib/src/runBuild.tsx b/desktop/pkg-lib/src/runBuild.tsx index ac07f17f4..020d5329a 100644 --- a/desktop/pkg-lib/src/runBuild.tsx +++ b/desktop/pkg-lib/src/runBuild.tsx @@ -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', },