Yes, you can load modules with wasm files into a create-react-app project. To do this, you will need to make some modifications to the CRA project. The following steps come from the Using WebAssembly with React tutorial by Richard Reedy:
Create the CRA:
npx create-react-app react-wasm-migration
Install react-app-rewired and wasm-loader dependencies:
npm install react-app-rewired wasm-loader -D
Add a config-overrides.js file with the following content:
const path = require('path');
module.exports = function override(config, env) {
const wasmExtensionRegExp = /\.wasm$/;
config.resolve.extensions.push('.wasm');
config.module.rules.forEach(rule => {
(rule.oneOf || []).forEach(oneOf => {
if (oneOf.loader && oneOf.loader.indexOf('file-loader') >= 0) {
// make file-loader ignore WASM files
oneOf.exclude.push(wasmExtensionRegExp);
}
});
});
// add a dedicated loader for WASM
config.module.rules.push({
test: wasmExtensionRegExp,
include: path.resolve(__dirname, 'src'),
use: [{ loader: require.resolve('wasm-loader'), options: {} }]
});
return config;
};
Change the CRA NPM Scripts to use react-app-rewired instead of react-scripts:
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test"
}
Install your wasm dependency:
npm install --save wasmlibfp
Asynchronously load the WASM in your JS code:
WebAssembly must be loaded asynchronously, so you will need to add JS code that loads it (I put this in App.js):
componentDidMount() {
this.loadWasm();
}
loadWasm = async () => {
try {
const wasm = await import('external');
this.setState({wasm});
} catch(err) {
console.error(`Unexpected error in loadWasm. [Message: ${err.message}]`);
}
};
Utilize the wasm code in the app if it has been loaded:
render() {
const { wasm = {} } = this.state;
return (
<div className="App">
{ wasm.doStuff && wasm.doStuff() }
</div>
);