如何将webAssembly脚本(wasm)集成到9号角项目中?

问题描述 投票:0回答:1

如何将webAssembly脚本(wasm)集成到angular 9项目中?

我通过将其添加到angular.json中来集成JS脚本,但是如何将webAssembly(WASM)文件添加到项目中?

angular typescript webassembly
1个回答
0
投票

[通过添加angular-wasm的依赖关系似乎可以实现

缺点是您似乎需要为wasm模块包括2个导入; 1是粘合代码,另一个是实际的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()
export 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)
      })
    )
  }
}

参考:https://malcoded.com/posts/web-assembly-angular/

© www.soinside.com 2019 - 2024. All rights reserved.