diff --git a/src/to-systemjs-worker.ts b/src/to-systemjs-worker.ts new file mode 100644 index 0000000..6b288cf --- /dev/null +++ b/src/to-systemjs-worker.ts @@ -0,0 +1,10 @@ +import { toSystemjs } from './to-systemjs.ts'; + +// @ts-ignore +self.addEventListener('message', async (event: MessageEvent<{ args: Parameters }>) => { + const transpiledCode = await toSystemjs(...event.data.args); + // @ts-ignore + self.postMessage({ code: transpiledCode }); + // @ts-ignore + self.close(); +}); diff --git a/src/to-systemjs.ts b/src/to-systemjs.ts index a2af923..43cb64c 100644 --- a/src/to-systemjs.ts +++ b/src/to-systemjs.ts @@ -6,7 +6,7 @@ import { rollupPluginVirtual, } from '../deps.ts'; -export const toSystemjs = async ( +export const toSystemjsMain = async ( esmCode: string, rollupOutputOptions: OutputOptions = {}, ): Promise => { @@ -34,3 +34,28 @@ export const toSystemjs = async ( await bundle.close(); return output[0].code; }; + +export const toSystemjsWorker = async ( + esmCode: string, + rollupOutputOptions: OutputOptions = {}, +): Promise => { + const worker = new Worker(import.meta.resolve('./to-systemjs-worker.ts'), { type: 'module' }); + return new Promise((resolve) => { + worker.addEventListener('message', (event: MessageEvent<{ code: string }>) => { + resolve(event.data.code); +}, false); + worker.postMessage({ + args: [esmCode, rollupOutputOptions], + }); + }); +} + +export const toSystemjs = async ( + esmCode: string, + rollupOutputOptions: OutputOptions = {}, +): Promise => { + if (typeof Worker !== 'undefined') { + return toSystemjsWorker(esmCode, rollupOutputOptions); + } + return toSystemjsMain(esmCode, rollupOutputOptions); +}