【问题标题】:implement webassembly angular 12 error load .wasm实现 webassembly angular 12 错误加载 .wasm
【发布时间】:2021-10-13 02:28:39
【问题描述】:

我尝试像这样将 .wasm 加载到我的项目中,它适用于 angular 5,但在 angular 12 时会出错

Blockquote ./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,其中包含您所面临问题的最低可重现版本吗?
  • 我不明白你为什么要为你的 wasm 使用文件加载器,如果你仍然要获取它?只需将其包含为资产

标签: javascript angular webassembly


【解决方案1】:

为了能够加载 wasm 文件,有一些要求,

首先,您必须确保您的 Web 服务器将 wasm 文件的 mime 类型报告为“application/wasm”。

接下来,您需要能够在 Angular 应用程序中加载 .wasm 文件。

如果你使用 webpack https://www.npmjs.com/package/wasm-loader 而不是文件加载器。 在 webpack5 中,包括电池。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多