diff --git a/README.md b/README.md index addf5ed..057c65e 100755 --- a/README.md +++ b/README.md @@ -59,12 +59,16 @@ When using the ESM version, Wasm is supported instead: ```js import { parse, init } from 'cjs-module-lexer'; -// init() needs to be called and waited upon, or use initSync() to compile -// Wasm blockingly and synchronously. +// In browsers, initialize the Wasm before parsing. await init(); const { exports, reexports } = parse(source); ``` +`parse` calls `initSync()` on first use if initialization has not completed. +Call `initSync()` directly to choose when the blocking initialization runs. +Browser main threads can restrict synchronous Wasm compilation, so await +`init()` before parsing in browsers. + The Wasm build is around 1.5x faster and without a cold start. ### Grammar diff --git a/src/lexer.js b/src/lexer.js index 30bca50..50e1961 100755 --- a/src/lexer.js +++ b/src/lexer.js @@ -4,7 +4,7 @@ const isLE = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1; export function parse (source, name = '@') { if (!wasm) - throw new Error('Not initialized'); + initSync(); const len = source.length + 1; diff --git a/test/_unit.js b/test/_unit.js index 0458f17..391d95e 100755 --- a/test/_unit.js +++ b/test/_unit.js @@ -20,6 +20,16 @@ async function loadParser () { suite('Lexer', () => { suiteSetup(async () => await loadParser()); + test('automatic Wasm initialization', async () => { + const lexer = await import('../dist/lexer.mjs?automatic-initialization'); + + assert.deepStrictEqual(lexer.parse('exports.value = 1'), { + exports: ['value'], + reexports: [] + }); + lexer.initSync(); + }); + test('export star failure', () => { parse(`__exportStar((0));`); });