Reputation: 7707
I’m trying to load this module into a create-react-app project: https://www.npmjs.com/package/wasmlibfp
When I do I get the following error:
./node_modules/wasmlibfp/wasmlibfp_bg.wasm
Module parse failed: magic header not detected
File was processed with these loaders:
* ./node_modules/file-loader/dist/cjs.js
You may need an additional loader to handle the result of these loaders.
Error: magic header not detected
Is there anything special I need to do to load wasm modules in CRA?
Upvotes: 7
Views: 4184
Reputation: 1248
Alternate you can try just create a normal react app then try to install the dependency.
npm install --save wasmlibfp
Upvotes: 0
Reputation: 3899
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:
npx create-react-app react-wasm-migration
react-app-rewired
and wasm-loader
dependencies:npm install react-app-rewired wasm-loader -D
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;
};
react-app-rewired
instead of react-scripts
:"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test"
}
npm install --save wasmlibfp
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}]`);
}
};
render() {
const { wasm = {} } = this.state;
return (
<div className="App">
{ wasm.doStuff && wasm.doStuff() }
</div>
);
Upvotes: 6