Webpack: asyncWebAssembly+importAwait


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 によるもの