首页 > 解决方案 > 如何在 Vite 和 Vue 3 中使用 Webassembly/wasm 模块?

问题描述

我正在尝试将 wasm 模块导入 vite vue 3 项目。 https://github.com/rsms/markdown-wasm


<script>
import init, { parse } from "markdown-wasm";

export default {
  async setup() {
    console.log(parse("# hello\n*world*"));
  },
};
</script>


它引发以下错误:

未捕获的语法错误:请求的模块“/@modules/markdown-wasm/dist/markdown.es.js”不提供名为“默认”的导出

我知道 wasm 需要异步加载。

在 vite 文档中,它说它需要以类似的方式导入。

import init from './example.wasm'

init().then(exports => {
  exports.test()
})

通过解构导入


import { parse, ready } from "markdown-wasm";

export default {
  async setup() {
    await ready;
  },
};

给出以下错误。

md.js:85 GET http://localhost:3000/markdown.wasm 404 (Not Found)
(anonymous) @ md.js:85
(anonymous) @ md.js:85
(anonymous) @ md.js:85
md.js:85 wasm streaming compile failed: TypeError: Failed to execute 'compile' on 'WebAssembly': HTTP status code is not ok
(anonymous) @ md.js:85
Promise.then (async)
(anonymous) @ md.js:85
Promise.then (async)
(anonymous) @ md.js:85
(anonymous) @ md.js:85
(anonymous) @ md.js:85
md.js:85 falling back to ArrayBuffer instantiation
(anonymous) @ md.js:85
Promise.then (async)
(anonymous) @ md.js:85
Promise.then (async)
(anonymous) @ md.js:85
(anonymous) @ md.js:85
(anonymous) @ md.js:85
md.js:85 GET http://localhost:3000/markdown.wasm 404 (Not Found)
r @ md.js:85
(anonymous) @ md.js:85
Promise.then (async)
(anonymous) @ md.js:85
Promise.then (async)
(anonymous) @ md.js:85
(anonymous) @ md.js:85
(anonymous) @ md.js:85
md.js:85 failed to asynchronously prepare wasm: Error: wasm abort: both async and sync fetching of the wasm failed
(anonymous) @ md.js:85
Promise.then (async)
r @ md.js:85
(anonymous) @ md.js:85
Promise.then (async)
(anonymous) @ md.js:85
Promise.then (async)
(anonymous) @ md.js:85
(anonymous) @ md.js:85
(anonymous) @ md.js:85
wlib.js:21 Uncaught (in promise) Error: wasm abort: Error: wasm abort: both async and sync fetching of the wasm failed
    at X (wlib.js:21)
    at Q (md.js:85)
    at md.js:85
    at X (wlib.js:21)
    at md.js:85

导入 wasm 模块的正确方法是什么?

标签: javascriptwebassemblyvuejs3vite

解决方案


推荐阅读