Skip to content

How to import WASM module, compiled from Rust with wasm-pack, into Preact project

Notifications You must be signed in to change notification settings

jorpic/preact-wasm-example

Repository files navigation

The most obvious way to import WASM

import('hello-wasm')
  .then(wasm => console.log(wasm))
  .catch(err => console.log(err));

Sadly, this fails at runtime with the following error:

TypeError: "__webpack_require__.w is undefined"
    wasm 0.chunk.c9660.esm.js:24
    __webpack_require__ bundle.esm.js:1470
    fn bundle.esm.js:830
    <anonymous> hello_wasm.js:1
    js 0.chunk.c9660.esm.js:11
    __webpack_require__ bundle.esm.js:1470
    fn bundle.esm.js:830

Seems like something in webpack is not implemented yet: webpack/webpack#7647.

Manual module initialization

// import js wrapper generated by wasm-bindgen
import { greet, default as init } from "hello-wasm";

// copy wasm to build dir
import hello from  "file-loader!hello-wasm/hello_wasm_bg.wasm";

// fetch and init module
init(hello)
  .then(res => console.log("greeting:", greet()))
  .catch(err => console.log(err));

Here we need to build WASM-module with wasm-pack build --target web.

Sadly, this also does not work as webpack tries to parse WASM file before handling it to file-loader.

✖ ERROR ./hello-wasm/pkg/hello_wasm_bg.wasm
Module parse failed: magic header not detected
You may need an appropriate loader to handle this file type.
Error: magic header not detected
...

Similar problem is described in webpack/webpack#8412. It can be fixed with this simple (yet undocumented) trick:

export default (config, env, helpers) => {
  config.module.defaultRules = [
    { type: 'javascript/auto', resolve: {} }
  ];
}

About

How to import WASM module, compiled from Rust with wasm-pack, into Preact project

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published