Brandon Durham
Brandon Durham

Reputation: 7707

Can you load modules with wasm files into create-react-app?

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

Answers (2)

Raushan Kumar
Raushan Kumar

Reputation: 1248

Alternate you can try just create a normal react app then try to install the dependency.

npm install --save wasmlibfp

Upvotes: 0

Daniel Bank
Daniel Bank

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:

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>
);

Upvotes: 6

Related Questions