[英]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我正在尝试将此模块加载到 create-react-app 项目中: 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?在 CRA 中加载 wasm 模块需要做些什么特别的事情吗?
Yes, you can load modules with wasm files into a create-react-app project.是的,您可以将带有 wasm 文件的模块加载到 create-react-app 项目中。 To do this, you will need to make some modifications to the CRA project.
为此,您需要对 CRA 项目进行一些修改。 The following steps come from the Using WebAssembly with React tutorial by Richard Reedy:
以下步骤来自 Richard Reedy 的Using WebAssembly with React 教程:
npx create-react-app react-wasm-migration
react-app-rewired
and wasm-loader
dependencies:react-app-rewired
rewired 和wasm-loader
依赖项:npm install react-app-rewired wasm-loader -D
config-overrides.js
file with the following content:config-overrides.js
文件: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
:react-app-rewired
而不是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
): WebAssembly 必须异步加载,因此您需要添加加载它的 JS 代码(我把它放在
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>
);
Alternate you can try just create a normal react app then try to install the dependency.或者,您可以尝试创建一个普通的反应应用程序,然后尝试安装依赖项。
npm install --save wasmlibfp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.