'implement webassembly angular 12 error load .wasm

I try to load .wasm into my project like that, it's work for angular 5 but get error when in angular 12

Blockquote ./node_modules/file-loader/dist/cjs.js?name=wasm/fibonacci.wasm!./wasm/fibonacci.wasm - Error: Module parse failed: magic header not detected

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)
      })
    )
  }
}


Solution 1:[1]

To be able to load a wasm file, there are some requirements,

At first, you have to be sure your web server reports wasm files mime type as 'application/wasm'.

Next, you will need being able to load .wasm file in your angular application.

if you use webpack < 4 , you may use https://www.npmjs.com/package/wasm-loader and not file-loader. in webpack5 , that 's battery included.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sancelot