Skip to content

Commit d225d68

Browse files
authored
Init Wasm module only once in browsers (parcel-bundler#615)
1 parent 0cc21e8 commit d225d68

File tree

1 file changed

+15
-10
lines changed

1 file changed

+15
-10
lines changed

wasm/index.mjs

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,29 @@
11
import { Environment, napi } from 'napi-wasm';
22
import { await_promise_sync, createBundleAsync } from './async.mjs';
33

4-
let wasm, bundleAsyncInternal;
4+
let wasm, initPromise, bundleAsyncInternal;
55

66
export default async function init(input) {
7+
if (wasm) return;
8+
if (initPromise) {
9+
await initPromise;
10+
return;
11+
}
12+
713
input = input ?? new URL('lightningcss_node.wasm', import.meta.url);
814
if (typeof input === 'string' || (typeof Request === 'function' && input instanceof Request) || (typeof URL === 'function' && input instanceof URL)) {
915
input = fetchOrReadFromFs(input);
1016
}
1117

12-
const { instance } = await load(await input, {
13-
env: {
14-
...napi,
15-
await_promise_sync
16-
}
17-
});
18+
initPromise = input
19+
.then(input => load(input, {env: {...napi, await_promise_sync}}))
20+
.then(({instance}) => {
21+
let env = new Environment(instance);
22+
bundleAsyncInternal = createBundleAsync(env);
23+
wasm = env.exports;
24+
});
1825

19-
let env = new Environment(instance);
20-
wasm = env.exports;
21-
bundleAsyncInternal = createBundleAsync(env);
26+
await initPromise;
2227
}
2328

2429
export function transform(options) {

0 commit comments

Comments
 (0)