WebAssembly Binary Module Loader for Webpack

raw JSON →
1.3.0 verified Mon Apr 27 auth: no javascript maintenance

A Webpack loader that allows importing .wasm binary files directly into JavaScript bundles as constructor functions returning a Promise resolving to WebAssembly.Instance. Current stable version 1.3.0. It eliminates the need for manual fetch and instantiation, converting wasm bytes to Uint8Arrays embedded in the JS bundle. Differentiators include optional dead code elimination via `dce=1` query parameter and support for passing custom import objects. Requires Webpack and Node.js, with peer dependency on wasm-dce. Suitable for basic wasm modules; for complex Emscripten output, custom imports are necessary.

error Module parse failed: Unexpected token (1:0) You may need an appropriate loader to handle this file type.
cause Webpack missing wasm-loader rule for .wasm files.
fix
Add { test: /\.wasm$/, use: 'wasm-loader' } to module.rules in webpack.config.js.
error TypeError: createInstance is not a function
cause Default import not returning function; possibly using wrong import syntax or loader not applied.
fix
Ensure webpack config applies wasm-loader to .wasm files and use correct import statement: import createInstance from './file.wasm'.
error Uncaught (in promise) LinkError: import object field 'env' is not an Object
cause Passed null or non-object as importsObject to the loader function.
fix
Ensure importsObject argument is a plain object with appropriate properties (e.g., { env: { memory: ..., table: ... } }).
breaking Loader returns a function returning Promise<WebAssembly.Instance>, not the instance directly.
fix Use '.then()' to access instance or await the promise.
gotcha Default importsObject may not satisfy complex Emscripten-compiled modules; custom imports required.
fix Pass custom import object to the loader function matching module expectations.
deprecated Dead code elimination via ?dce=1 is experimental and may not work with all wasm features.
fix Test thoroughly and consider alternatives if DCE fails.
gotcha wasm files become part of JS bundle, increasing bundle size; not suitable for large wasm modules.
fix Consider separate loading strategies (e.g., dynamic import) for large wasm.
npm install wasm-loader
yarn add wasm-loader
pnpm add wasm-loader

Shows how to configure Webpack with wasm-loader and use the default export to instantiate a WebAssembly module and call an exported function.

// webpack.config.js
module.exports = {
  module: {
    rules: [
      { test: /\.wasm$/, use: 'wasm-loader' }
    ]
  }
};

// app.js
import createInstance from './factorial.wasm';

createInstance().then(instance => {
  const factorial = instance.exports._Z4facti;
  console.log(factorial(5)); // 120
}).catch(err => console.error(err));