To use WebAssembly (WASM) in a Create React App project, follow these steps:
-
Create a React application (if you haven't already): Use the Create React App CLI to create a new React application:
shnpx create-react-app my-react-app cd my-react-app -
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):
shcurl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh cargo install wasm-pack -
Create a new Rust library:
shcargo new --lib my-wasm-library cd my-wasm-library -
Add wasm-bindgen as a dependency in the
Cargo.tomlfile:toml[lib] crate-type = ["cdylib"] [dependencies] wasm-bindgen = "0.2" -
Write your Rust code and export functions using
wasm-bindgeninsrc/lib.rs:rustuse wasm_bindgen::prelude::*; #[wasm_bindgen] pub fn greet(name: &str) -> String { return format!("Hello, {}!", name); } -
Build the WebAssembly module using wasm-pack:
shwasm-pack build --target web
-
-
Integrate WASM into the React application: Place the built WebAssembly files in the
publicfolder of your React application, or include them by configuring Webpack (if you have ejected Create React App). -
Load and use WASM modules: In React components, you can load WASM modules using
fetchandWebAssembly.instantiateStreaming(or use theimportstatement if you use the--target bundleroption with wasm-pack).For example, in
src/App.js:javascriptimport 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; -
Run the application: Now, you can run your React application, which will load the WebAssembly module.
shnpm 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).