From 48af7442dce3ce188b0332f35021d5f60f7aa8bb Mon Sep 17 00:00:00 2001 From: Niklas Mischkulnig <4586894+mischnic@users.noreply.github.com> Date: Fri, 27 Oct 2023 20:37:54 +0200 Subject: [PATCH 1/2] Init Wasm module only once in browsers --- wasm/index.mjs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/wasm/index.mjs b/wasm/index.mjs index 0b049b50..6f948787 100644 --- a/wasm/index.mjs +++ b/wasm/index.mjs @@ -4,6 +4,8 @@ import { await_promise_sync, createBundleAsync } from './async.mjs'; let wasm, bundleAsyncInternal; export default async function init(input) { + if (wasm) return; + input = input ?? new URL('lightningcss_node.wasm', import.meta.url); if (typeof input === 'string' || (typeof Request === 'function' && input instanceof Request) || (typeof URL === 'function' && input instanceof URL)) { input = fetchOrReadFromFs(input); From f1685496aa2b65a90561e857948a383c77cf5a10 Mon Sep 17 00:00:00 2001 From: Niklas Mischkulnig <4586894+mischnic@users.noreply.github.com> Date: Sat, 28 Oct 2023 14:36:02 +0200 Subject: [PATCH 2/2] Init Wasm only once when loading multiple times --- wasm/index.mjs | 23 +++++++++++++---------- 1 file changed, 13 insertions(+), 10 deletions(-) diff --git a/wasm/index.mjs b/wasm/index.mjs index 6f948787..aba5596d 100644 --- a/wasm/index.mjs +++ b/wasm/index.mjs @@ -1,26 +1,29 @@ import { Environment, napi } from 'napi-wasm'; import { await_promise_sync, createBundleAsync } from './async.mjs'; -let wasm, bundleAsyncInternal; +let wasm, initPromise, bundleAsyncInternal; export default async function init(input) { if (wasm) return; + if (initPromise) { + await initPromise; + return; + } input = input ?? new URL('lightningcss_node.wasm', import.meta.url); if (typeof input === 'string' || (typeof Request === 'function' && input instanceof Request) || (typeof URL === 'function' && input instanceof URL)) { input = fetchOrReadFromFs(input); } - const { instance } = await load(await input, { - env: { - ...napi, - await_promise_sync - } - }); + initPromise = input + .then(input => load(input, {env: {...napi, await_promise_sync}})) + .then(({instance}) => { + let env = new Environment(instance); + bundleAsyncInternal = createBundleAsync(env); + wasm = env.exports; + }); - let env = new Environment(instance); - wasm = env.exports; - bundleAsyncInternal = createBundleAsync(env); + await initPromise; } export function transform(options) {