reactjs 用react-ts和vitejs加载wasm

2vuwiymt  于 2023-06-22  发布在  React
关注(0)|答案(1)|浏览(166)

尝试离开webpack和create-react-app为vitejs。但是在WASM文件中遇到问题。

import init from "swaplab2/dist/swaplab2.wasm?init";
import { setSwaplab2 } from "swaplab2";

export function TestPage(): React.ReactElement {
    const [swaplab2Loaded, setSwaplab2Loaded] = useState(false);

    useEffect(() => {
        //https://vitejs.dev/guide/features.html#webassembly
        if (!swaplab2Loaded) {
            init({})
                .then((instance) => {
                    setSwaplab2(instance);
                    setSwaplab2Loaded(true);
                })
        }
    });

但是得到一个错误

TypeError: WebAssembly.instantiate(): Import #0 module="env" error: module is not an object or function

如果我加上类似

init({ env: import.meta.env })

我反而得到

TypeError: WebAssembly.instantiate(): Import #72 module="wasi_snapshot_preview1" error: module is not an object or function

感觉我走错路了,希望你能指点一下

1bqhqjot

1bqhqjot1#

Swaplab2在没有独立交换机的情况下编译,使用emscripten ABI而不是WASI https://github.com/emscripten-core/emscripten/wiki/WebAssembly-Standalone
和vitejs在一起很容易

import swaplab2Url from "swaplab2/dist/swaplab2.wasm?url";
import { Swaplab2Module, setSwaplab2 } from "swaplab2";

export function TestPage(): React.ReactElement {
    const [swaplab2Loaded, setSwaplab2Loaded] = useState(false);

    useEffect(() => {
        //https://vitejs.dev/guide/features.html#webassembly
        if (!swaplab2Loaded) {
            Swaplab2Module({ locateFile: (path) => (path.endsWith(".wasm") ? swaplab2Url : path) }).then((loaded) => {
                setSwaplab2(loaded);
                setSwaplab2Loaded(true);
            });
        }
    });

相关问题