reactjs 如何在TypeScript中使用Astro和WASM

rn0zuynd  于 2022-11-22  发布在  React
关注(0)|答案(1)|浏览(162)

我想在我的Astro应用程序中使用我在Rust中编写的Web-Assembly模块。我正在使用TypeScript和以下astro.config.mjs

import { defineConfig } from "astro/config";
import wasm from "vite-plugin-wasm";
import topLevelAwait from "vite-plugin-top-level-await";

import tailwind from "@astrojs/tailwind";
import react from "@astrojs/react";

export default defineConfig({
  integrations: [wasm(), tailwind(), react()],
  vite: {
    plugins: [wasm(), topLevelAwait()],
  },
});

在文件functions.ts中使用wasm的代码如下所示:

import { greet } from "dices";

export function hello(): void {
  let g: string = greet();
  console.log(g);
}

类型检查工作正常,但是在运行npm run dev时遇到以下错误:

error   WebAssembly.instantiate(): BufferSource argument is empty
CompileError: WebAssembly.instantiate(): BufferSource argument is empty        
    at Module.__vite_ssr_exports__.default (/__vite-plugin-wasm-helper:31:14)  
    at processTicksAndRejections (node:internal/process/task_queues:96:5)      
    at async eval (/pkg/dices_bg.wasm:6:28)
    at async instantiateModule (file:///D:/code/web-dev/dice-calculator-frontend/node_modules/vite/dist/node/chunks/dep-4da11a5e.js:53445:9)

当我通过npm create vite@latest使用React和TypeScript设置一个新的Vite项目时,使用相同的functions.ts文件和以下vite.config.ts,一切正常,我可以使用wasm模块中的函数,没有问题。
vite.config.ts

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

import wasm from "vite-plugin-wasm";
import topLevelAwait from "vite-plugin-top-level-await";

export default defineConfig({
  plugins: [react(), wasm(), topLevelAwait()],
});

有没有人让WASM与Astro合作?我有点困惑,因为Astro在引擎盖下使用Vite,但什么工作正常,只是Vite,似乎不工作与Astro。

azpvetkf

azpvetkf1#

我发现使用

<DistributionCalculatorWrapper client:only="react" />

代替

<DistributionCalculatorWrapper client:load />

是一个适合我的解决方案。我猜Node.js不能使用wasm服务器端是有问题的,但是如果我们显式地让使用wasm函数的组件只在客户端用client:only="react"呈现,它就可以工作。

相关问题