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

How to use WebAssembly ( wasm ) with create- react - app

1个答案

1

To use WebAssembly (WASM) in a Create React App project, follow these steps:

  1. Create a React application (if you haven't already): Use the Create React App CLI to create a new React application:

    sh
    npx create-react-app my-react-app cd my-react-app
  2. Create your WebAssembly code: You need to write your code in C, C++, Rust, or other languages that can be compiled to WASM. For example, using Rust:

    • Install Rust and wasm-pack (if not already installed):

      sh
      curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh cargo install wasm-pack
    • Create a new Rust library:

      sh
      cargo new --lib my-wasm-library cd my-wasm-library
    • Add wasm-bindgen as a dependency in the Cargo.toml file:

      toml
      [lib] crate-type = ["cdylib"] [dependencies] wasm-bindgen = "0.2"
    • Write your Rust code and export functions using wasm-bindgen in src/lib.rs:

      rust
      use wasm_bindgen::prelude::*; #[wasm_bindgen] pub fn greet(name: &str) -> String { return format!("Hello, {}!", name); }
    • Build the WebAssembly module using wasm-pack:

      sh
      wasm-pack build --target web
  3. Integrate WASM into the React application: Place the built WebAssembly files in the public folder of your React application, or include them by configuring Webpack (if you have ejected Create React App).

  4. Load and use WASM modules: In React components, you can load WASM modules using fetch and WebAssembly.instantiateStreaming (or use the import statement if you use the --target bundler option with wasm-pack).

    For example, in 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. Run the application: Now, you can run your React application, which will load the WebAssembly module.

    sh
    npm start

The above are the basic steps to integrate and use WebAssembly modules in a Create React App project. Adjust according to your specific scenario. Note that the way to load WebAssembly modules may vary depending on the programming language and toolchain you use (e.g., using Emscripten instead of Rust and wasm-pack).

2024年6月29日 12:07 回复

你的答案