我将create-react-app和库与wasm一起使用,称为sax-wasm
稍微修改网络的示例代码,我得到了:

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命令时,我的构建失败了:
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
CRA不支持WASM。但是您可以解决它。您需要覆盖webpack配置。有多个软件包可以做到这一点。我使用了react-app-rewired。而且您需要wasm-loader软件包
比添加您的覆盖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"
  }
}

关于webpack - 如何在create-react-app中使用WebAssembly(wasm),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59319775/

10-10 13:11