Rust wasm 在下一个 js 中

2023-12-31

我正在尝试在我的 NextJs 项目中使用 rust 生成的 wasm 模块。

我通过以下方式导入 wasm:

import init, { tokenize } from "@/wasm/lazyjson";

const Test = dynamic({
    loader: async () => {
        await init();

        console.log(tokenize("[]"));

        return function Yay() {
            return <p>hi</p>;
        };
    },
});

我还尝试使用以下方式导入它:

const { default: init, tokenize } = await import("@/wasm/lazyjson");

这导致

TypeError: Only absolute URLs are supported

从 webpack 5(NextJs 使用的)开始,默认支持 WebAssembly(我认为)。所以这是我的next.config.js/ 网页包配置:

module.exports = {
    webpack: (config) => {
        config.resolve.alias["@/"] = __dirname;

        return config;
    },
};

我尝试添加syncWebAssembly flag

config.experiments = { syncWebAssembly: true };

这会导致不同的错误:

Module not found: Can't resolve 'wbg' in '[project-path]\wasm\lazyjson'

如果您对这个问题感到困惑或需要更多背景信息,请查看我打开的问题here https://github.com/vercel/next.js/issues/27083。它还包含重现步骤。


不要依赖第三方库,而是将 wasm 文件夹放入public文件夹并简单地在客户端获取它。

async function getWasm() {
  try {
    const res = await fetch("test.wasm");
    // bytes from memory
    const buffer = await res.arrayBuffer();
    // this will create an object
    // WebAssembly is part of window api. so make sure you are on client side. 
    const wasm = await WebAssembly.instantiate(buffer);
    console.log(wasm);
    // this is the method defined in wasm code
    // you need to know what methods are defined in your source code
    const addNumbers = wasm.instance.exports.addTwo;
    // console.log(addNumbers);
    const result = addNumbers(100, 50);
    console.log(result);
  } catch (e) {
    console.log(e);
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Rust wasm 在下一个 js 中 的相关文章

随机推荐