Skip to content

Commit

Permalink
Init Wasm module only once in browsers (#615)
Browse files Browse the repository at this point in the history
  • Loading branch information
mischnic committed Oct 30, 2023
1 parent 0cc21e8 commit d225d68
Showing 1 changed file with 15 additions and 10 deletions.
25 changes: 15 additions & 10 deletions wasm/index.mjs
@@ -1,24 +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) {
Expand Down

0 comments on commit d225d68

Please sign in to comment.