我遵循了wasm -bindgen的Hello World 指南(我正在使用)。wasm-bindgen = "0.2.72"
不幸的是,指南中提到的 npm 包并不是最新的。因为我想有一个干净的起点,所以我尝试升级它们。
这是package.json
指南中提到的:
{
"scripts": {
"build": "webpack",
"serve": "webpack-dev-server"
},
"devDependencies": {
"@wasm-tool/wasm-pack-plugin": "1.0.1",
"text-encoding": "^0.7.0",
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.29.4",
"webpack-cli": "^3.1.1",
"webpack-dev-server": "^3.1.0"
}
}
我删除text-encoding
(因为我不关心不支持非基于 Chromium 的Edge版本)并升级@wasm-tool/wasm-pack-plugin
没有问题:
工作package.json
:
{
"scripts": {
"build": "webpack",
"serve": "webpack-dev-server"
},
"devDependencies": {
"@wasm-tool/wasm-pack-plugin": "^1.3.3",
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.29.4",
"webpack-cli": "^3.1.1",
"webpack-dev-server": "^3.1.0"
}
}
工作webpack.config.js
:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const WasmPackPlugin = require("@wasm-tool/wasm-pack-plugin");
module.exports = {
entry: './index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index.js',
},
plugins: [
new HtmlWebpackPlugin({
template: 'index.html'
}),
new WasmPackPlugin({
crateDirectory: path.resolve(__dirname, ".")
})
],
mode: 'development'
};
我做的下一件事是升级html-webpack-plugin
andwebpack
本身。
有错误的package.json
版本:
{
"scripts": {
"build": "webpack",
"serve": "webpack-dev-server"
},
"devDependencies": {
"@wasm-tool/wasm-pack-plugin": "^1.3.3",
"html-webpack-plugin": "^5.3.1",
"webpack": "^5.27.1",
"webpack-cli": "^3.1.1",
"webpack-dev-server": "^3.1.0"
}
}
因为我升级webpack
到版本5.27.1
,所以我也不得不改变webpack.config.js
这样的:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const WasmPackPlugin = require("@wasm-tool/wasm-pack-plugin");
module.exports = {
entry: './index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'index.js',
},
plugins: [
new HtmlWebpackPlugin({
template: 'index.html'
}),
new WasmPackPlugin({
crateDirectory: path.resolve(__dirname, ".")
})
],
experiments: {
asyncWebAssembly: true
},
mode: 'development'
};
现在,当我运行npm run serve
构建完成时没有错误,但是当我打开网页时,不再显示任何警报。现在在浏览器控制台中记录了以下错误:
TypeError: _index_bg_wasm__WEBPACK_IMPORTED_MODULE_0__ is undefined
greet webpack:///./pkg/index_bg.js?:113
<anonymous> webpack:///./index.js?:4
promise callback* webpack:///./index.js?:4
js http://localhost:8080/index.js:18
__webpack_require__ http://localhost:8080/index.js:366
<anonymous> http://localhost:8080/index.js:709
<anonymous> http://localhost:8080/index.js:712
我该怎么做才能摆脱这个问题,以便我可以使用wasm-bindgen
with webpack ^5.27.1
?
我很感谢任何提示。
额外观察
有趣的是,我发现,即使使用不工作的版本,也可以像这样m => m.greet('World!')
删除index.js
并调用 wasm 函数pkg/index.js
import * as wasm from "./index_bg.wasm";
export * from "./index_bg.js";
wasm.greet("World");
当我这样做时,我在控制台中不再出现错误,并且显示“你好,!”的警报 (缺少“世界”)已显示,所以我认为 .wasm 应该仍然可以......
更新
通过使用,我能够让一切恢复正常:
experiments: {
syncWebAssembly: true
},
但是这已被弃用,所以如果有办法仍然使用asyncWebAssembly
.