乐闻世界logo
搜索文章和话题

如何将 WebAssembly ( wasm )与 create- react -app 一起使用?

4 个月前提问
3 个月前修改
浏览次数39

1个答案

1

要在Create React App项目中使用WebAssembly(WASM),你需要遵循以下步骤:

  1. 创建React应用程序(如果你还没有的话): 使用Create React App CLI来创建一个新的React应用程序:

    sh
    npx create-react-app my-react-app cd my-react-app
  2. 创建你的WebAssembly代码: 你需要用C、C++、Rust或其他能编译成WASM的语言写你的代码。比如,使用Rust:

    • 安装Rust和wasm-pack(如果尚未安装):

      sh
      curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh cargo install wasm-pack
    • 创建一个新的Rust库:

      sh
      cargo new --lib my-wasm-library cd my-wasm-library
    • Cargo.toml中添加wasm-bindgen作为依赖项:

      toml
      [lib] crate-type = ["cdylib"] [dependencies] wasm-bindgen = "0.2"
    • 编写你的Rust代码并使用wasm-bindgen导出函数,在src/lib.rs中:

      rust
      use wasm_bindgen::prelude::*; #[wasm_bindgen] pub fn greet(name: &str) -> String { return format!("Hello, {}!", name); }
    • 使用wasm-pack构建WebAssembly模块:

      sh
      wasm-pack build --target web
  3. 在React应用程序中集成WASM: 把构建好的WebAssembly文件放到你的React应用程序的public文件夹中,或者通过配置Webpack(如果你'ejected'了Create React App)来包含这些文件。

  4. 加载和使用WASM模块: 在React组件中,你可以使用fetchWebAssembly.instantiateStreaming(或者如果你使用wasm-pack的--target bundler选项,可以使用import语句)来加载WASM模块。

    例如,在src/App.js中:

    javascript
    import React, { useState, useEffect } from 'react'; const App = () => { const [wasmModule, setWasmModule] = useState(null); useEffect(() => { const initWasm = async () => { try { const wasm = await import('my-wasm-library/my_wasm_library.js'); setWasmModule(wasm); } catch (err) { console.error('Error loading WASM module:', err); } }; initWasm(); }, []); const greet = () => { if (wasmModule) { const greeting = wasmModule.greet('World'); console.log(greeting); } }; return ( <div> <button onClick={greet}>Greet</button> </div> ); }; export default App;
  5. 运行应用程序: 现在,你可以运行你的React应用程序,并且会加载WebAssembly模块。

    sh
    npm start

以上就是在Create React App项目中集成和使用WebAssembly模块的基本步骤。请根据你的具体场景进行调整。注意,WebAssembly模块的加载方式可能因你使用的编程语言和工具链(例如,使用Emscripten而不是Rust和wasm-pack)而异。

2024年6月29日 12:07 回复

你的答案