4
2

More than 3 years have passed since last update.

Webpack: asyncWebAssembly+importAwait

Posted at

wasmのダイナミックimportsとモジュール解決してくれる内部プラグインがWebpack v5.0から入っていた。

webpack.config.js
module.exports = {
    entry: "./example.js",
    output: {
        webassemblyModuleFilename: "[hash].wasm",
        publicPath: "dist/",
        filename: "output.js"
    },
    module: {
        rules: [
            {
                test: /\.wasm$/,
                type: "webassembly/async"
            }
        ]
    },
    experiments: {
        asyncWebAssembly: true,
        importAwait: true
    }
};
example.js
import await { add } from "./add.wasm";

console.log(add(22, 2200));
index.html
<html>
    <body>
        <script src="dist/output.js"></script>
    </body>
</html>

内部的にはfetchして WebAssembly.instantiateStreaming() に食わせてexportsを Object.assing() してモジュールを解決してくれるっぽい。

npx http-server ではwasmファイルのcontent-type指定がGoogle Chromeで動作しなく、かわりに ecstatic を使った。

$ webpack -v
5.0.0-beta.23

$ webpack && ecstatic

$ open http://127.0.0.1:8000/

ソースコードは examples/wasm-simple によるもの

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2