You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vue+Vite中使用Go编写的Wasm函数(含Pinia场景)

解决方案:在Vue + Vite中集成Go WebAssembly

1. 正确处理wasm_exec.js依赖

Go编译的Wasm必须依赖官方的wasm_exec.js,但它并非ES模块,直接导入会触发解析错误。正确做法:

  • 从Go安装目录复制wasm_exec.js到项目public目录(如public/wasm_exec.js)
  • 在项目根目录的index.html中通过全局脚本标签引入,而非在Vue组件/Pinia内导入:
    <script src="/wasm_exec.js"></script>
    
    引入后全局环境会自动提供Go构造函数。

2. 编译Go代码为Wasm的标准命令

编译时指定目标环境,并将输出文件放到Vite可访问的目录(如public/):

GOOS=js GOARCH=wasm go build -o public/main.wasm ./main.go

3. 在Pinia Store中加载并运行Wasm

在Pinia的action里,通过全局Go实例完成Wasm的实例化与运行,不要使用Vite默认的Wasm导入方式:

// src/store/wasmStore.js
import { defineStore } from 'pinia'

export const useWasmStore = defineStore('wasm', {
  actions: {
    async loadGoWasm() {
      const go = new Go()
      // 加载编译好的Wasm文件
      const response = await fetch('/main.wasm')
      const bytes = await response.arrayBuffer()
      // 传入Go的importObject解决模块依赖问题
      const result = await WebAssembly.instantiate(bytes, go.importObject)
      // 启动Wasm程序
      go.run(result.instance)

      // 调用Go通过syscall/js暴露到window的函数(示例:假设Go端定义了add函数)
      console.log(window.add(1, 2))
    }
  }
})

4. Vite配置补充

添加跨域安全头,避免Wasm加载时的权限错误,修改vite.config.js:

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

export default defineConfig({
  plugins: [vue()],
  server: {
    headers: {
      'Cross-Origin-Embedder-Policy': 'require-corp',
      'Cross-Origin-Opener-Policy': 'same-origin'
    }
  }
})

常见错误排查

  • Import #0 module="go" error:未传入Go的importObject,必须将new Go().importObject作为第二个参数传给WebAssembly.instantiate
  • Failed to resolve import "go":禁止在ES模块中导入wasm_exec.js,必须全局引入
  • 若尝试vite-plugin-wasm,需搭配vite-plugin-top-level-await,但全局引入wasm_exec.js的方式更稳定

内容的提问来源于stack exchange,提问作者beagledrive

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 20:54:26