How to import built WASM modules
vite.config.js generates aliases of the form @wasm-{module} that map to src/wasm/modules/{module}/build at resolve time. This makes importing convenient:
// example: import the JS bootstrap generated by emscripten
import initWasmModule from '@wasm-image/index.js';
// use it
async function loadImageWasm() {
const wasmModule = await initWasmModule();
// wasmModule now contains exported functions / EM_JS wrappers / Module.
}
note
Emscripten-generated builds often export a JS wrapper (index.js) that bootstraps loading of index.wasm. Vite must copy .wasm files into the final dist — assetsInclude: ['**/*.wasm'] is already set in this project to ensure this.
Best practices
- Always
awaitthe module initializer before calling exported functions. - Keep the Emscripten API surface small — expose only functions you need via
extern "C"and a small header such asexported.h. - Return simple typed arrays or pointers + lengths; avoid passing large JS objects across the bridge.
Example: small wrapper hook
// src/hooks/useImageWasm.js
import { useEffect, useState } from 'react';
import init from '@wasm-image/index.js';
export default function useImageWasm() {
const [module, setModule] = useState(null);
useEffect(() => {
let mounted = true;
init().then((m) => { if (mounted) setModule(m); });
return () => { mounted = false; };
}, []);
return module;
}