实现WebAssembly Angular 12错误加载.wasm

3

我试图像这样将.wasm加载到我的项目中,这对于Angular 5有效,但在Angular 12中出现错误:

引用./node_modules/file-loader/dist/cjs.js?name=wasm/fibonacci.wasm!./wasm/fibonacci.wasm - 错误:模块解析失败:未检测到魔术头

import { Injectable } from '@angular/core'
import { Observable, BehaviorSubject } from 'rxjs'
import { filter, map } from 'rxjs/operators'

import * as Module from './../../wasm/fibonacci.js'
import '!!file-loader?name=wasm/fibonacci.wasm!../../wasm/fibonacci.wasm'

@Injectable()
class WasmService {
  module: any

  wasmReady = new BehaviorSubject<boolean>(false)

  constructor() {
    this.instantiateWasm('wasm/fibonacci.wasm')
  }

  private async instantiateWasm(url: string) {
    // fetch the wasm file
    const wasmFile = await fetch(url)

    // convert it into a binary array
    const buffer = await wasmFile.arrayBuffer()
    const binary = new Uint8Array(buffer)

    // create module arguments
    // including the wasm-file
    const moduleArgs = {
      wasmBinary: binary,
      onRuntimeInitialized: () => {
        this.wasmReady.next(true)
      },
    }

    // instantiate the module
    this.module = Module(moduleArgs)
  }

  public fibonacci(input: number): Observable<number> {
    return this.wasmReady.pipe(filter(value => value === true)).pipe(
      map(() => {
        return this.module._fibonacci(input)
      })
    )
  }
}

您是否可以创建一个 stackblitz,并提供一个最小可重现的版本,以便我们更好地解决您所面临的问题? - The Fabio
如果你已经在获取wasm文件,我不明白为什么你要使用文件加载器?直接将其作为资源包含即可。 - bryan60
1个回答

0
为了能够加载wasm文件,有一些要求:
首先,您必须确保您的Web服务器将wasm文件的MIME类型报告为“application/wasm”。
接下来,您需要能够在您的Angular应用程序中加载.wasm文件。
如果您使用webpack <4,则可以使用https://www.npmjs.com/package/wasm-loader而不是file-loader。在webpack5中,这已经默认包含了。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接