如何在create-react-app中使用WebAssembly(wasm) [英] How to use WebAssembly (wasm) with create-react-app

查看:195
本文介绍了如何在create-react-app中使用WebAssembly(wasm)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 create-react-app 和库与 wasm 一起使用,称为

I use create-react-app and library with wasm its called sax-wasm. Slightly modifying the sample code for the web I got this:

import { SaxEventType, SAXParser } from 'sax-wasm';

async function loadAndPrepareWasm() {
  const saxWasmResponse = await import('sax-wasm/lib/sax-wasm.wasm');
  const saxWasmbuffer = await saxWasmResponse.arrayBuffer();
  const parser = new SAXParser(SaxEventType.Attribute | SaxEventType.OpenTag, {
    highWaterMark: 64 * 1024,
  });

  const ready = await parser.prepareWasm(new Uint8Array(saxWasmbuffer));
  if (ready) {
    return parser;
  }
}

loadAndPrepareWasm().then(console.log);

当我运行 yarn start 命令时,我的构建失败:

When I running yarn start command my build is failed:

Failed to compile.

./node_modules/sax-wasm/lib/sax-wasm.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

推荐答案

以下解决方案适用于CRA3.x.对于CRA 4.x,您应该使用 craco .

The following solution is for CRA 3.x. For CRA 4.x you should use craco.

CRA不支持WASM.但是您可以解决它.您需要覆盖webpack配置.有多个软件包可以做到这一点.我使用了 react-app-rewired .而且您需要wasm-loader程序包

CRA does not support WASM. But you can workaround it. You need to override webpack config. There are multiple packages that can do it. I used react-app-rewired. And you need the wasm-loader package

比添加您的替代 config-overrides.js :

const path = require('path');

module.exports = function override(config, env) {

    /**
     * Add WASM support
     */

    // Make file-loader ignore WASM files
    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) {
                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;
};

package.json 中,我是这样的:

{
...
  "scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-scripts eject",
    "predeploy": "npm run build",
    "deploy": "gh-pages -d build"
  },
...
  "devDependencies": {
    "react-app-rewired": "2.1.3",
    "wasm-loader": "1.3.0"
  }
}

这篇关于如何在create-react-app中使用WebAssembly(wasm)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆