基于wasm-pack构建的wasm要集成到vue工程中,总是遇到这样那样的错误。
错误一:
Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "application/wasm". Strict MIME type checking is enforced for module scripts per HTML spec.
错误二:
webAssembly module is included in initial chunk.This is not allowed, because WebAssembly download and compilation must happen asynchronousAdd an async splitpoint (i. e. import() somewhere between your entrypoint and the WebAssembly module:
经过各种百度、Google、chatGPT,最终确定了如下步骤:
1. 打包时,务必指定target为web,即:
wasm-pack build --release --target web
2. vue中引入模块:
将第一步打包的所有文件,放在src下的某个目录下,
import init, {
add // 一:这里要把wasm-bindgen标注的函数列到这里
} from "@/utils/wasm-demo";
export default {
name: 'App',
components: {
HelloWorld
},
methods:{
// 二:定义异步加载函数
async run(){
// 如果当前环境不支持import.meta.url,init函数需要直接传入wasm文件的路径,例如:
// await init('/public/wasm/wasm_demo_bg.wasm');
await init();
// 测试代码
console.log("测试"+add(1,2));
}
},
mounted: function(){
// 三: 调用异步加载函数
this.run();
}
}
3. 部分vue项目,由于babel/plugin-syntax-import-meta版本过低的缘故,不支持import.meta.url,需要对wasm-demo.js文件进行微调,把import.meta.url所在的代码行屏蔽掉。