我正在尝试将此模块加载到 create-react-app 项目中:https://www.npmjs.com/package/wasmlibfp
当我这样做时,我收到以下错误:
./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
在 CRA 中加载 wasm 模块需要做什么特别的事情吗?
最佳答案
是的,您可以将带有 wasm 文件的模块加载到 create-react-app 项目中。为此,您需要对 CRA 项目进行一些修改。以下步骤来自 Richard Reedy 的 Using WebAssembly with React tutorial:
创建 CRA:
npx create-react-app react-wasm-migration
安装
react-app-rewired
和 wasm-loader
依赖项:npm install react-app-rewired wasm-loader -D
添加一个
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;
};
更改 CRA NPM 脚本以使用
react-app-rewired
而不是 react-scripts
:"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test"
}
安装您的 wasm 依赖项:
npm install --save wasmlibfp
在 JS 代码中异步加载 WASM:
WebAssembly must be loaded asynchronously ,所以你需要添加加载它的 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}]`);
}
};
如果已加载,则在应用程序中使用 wasm 代码:
render() {
const { wasm = {} } = this.state;
return (
<div className="App">
{ wasm.doStuff && wasm.doStuff() }
</div>
);
关于javascript - 您可以将带有 wasm 文件的模块加载到 create-react-app 中吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58259904/