内容
MDN のチュートリアルページに従って Rust で WebAssembly を作ってみようとしたところよくわからないエラーで頓挫。そこでなんとか動くようにしてみました、という話です。
きっかけ
MDN Web Page の「Rust から WebAssembly にコンパイル」
に従い操作を進めたところ、最後の 'npm run serve' コマンドでエラーになりました。
% npm run serve
...
ERROR in ../pkg/hello_wasm_bg.wasm
Module parse failed: Unknown element type in table: 0xNaN
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
...
エラーの原因
エラーメッセージを頼りにいろいろ検索してみたところ、どうやら Rust の v1.82 以降と webpack 4 の相性がよくないらしいです。
解決策
webpack 4 のままでも回避策はあるらしいのですが、現行バージョンの webpack 5 に対応する方が前向きかなと思います。
まずは 'package.json' を直して webpack 5 対応にします。それに伴い 'webpack.config.js' も修正が必要になります。
具体的には以下の通り。
{
"scripts": {
"serve": "webpack-dev-server"
},
"dependencies": {
"hello-wasm": "^0.1.0"
},
"devDependencies": {
"webpack": "^5.98.0",
"webpack-cli": "^6.0.1",
"webpack-dev-server": "^5.2.1"
}
}
const path = require("path");
module.exports = {
entry: "./index.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "index.js",
},
mode: "development",
devServer: {
static: {
directory: path.join(__dirname, "/")
}
},
experiments: {
asyncWebAssembly: true
}
};
webpack のバージョンなどは適当に変更しても大丈夫かと。
'webpack.config.js' の 'experiments:' 部分ですが、これを入れないと
以下のようなエラーが出ます。エラーメッセージに従って 'asyncWebAssembly: true' を設定しました。
ERROR in ../pkg/hello_wasm_bg.wasm 1:0
Module parse failed: Unexpected character '' (1:0)
The module seem to be a WebAssembly module, but module is not flagged as WebAssembly module for webpack.
BREAKING CHANGE: Since webpack 5 WebAssembly is not enabled by default and flagged as experimental feature.
You need to enable one of the WebAssembly experiments via 'experiments.asyncWebAssembly: true' (based on async modules) or 'experiments.syncWebAssembly: true' (like webpack 4, deprecated).
まとめ
無事 Rust で作った 'hello_wasm' が動きました。