Vue 组件加载 WASM 模块的最简方法

基于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所在的代码行屏蔽掉。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT 行者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值