Importing and compiling a module with wasm into webpack
Asked Answered
T

1

10

I'm trying to import a module for use within a library which is compiled through webpack. Although the javascript API from the module is loaded, the accompanying .wasm file is not and causes any functions mentioning the wasm module to throw undefined errors. There is also the possibility that webpack is interfering with the .wasm file but I'm not sure. Here is the error.

Uncaught (in promise) TypeError: _index_bg_wasm__WEBPACK_IMPORTED_MODULE_0__.open_image is not a function
    at Module.open_image (index_bg.js?0d72:1468)

And the associated function call

import('@silvia-odwyer/photon').then(photon => {
  console.log(photon.open_image) // <-- correctly prints function
  let ctx = canvas.getContext('2d');
  let photonImg = photon.open_image(canvas, ctx); // <-- error
  photon.grayscale(photonImg);
  photon.putImageData(canvas, ctx, photonImg);
});

I have tried using wasm-loader, editing my tsconfig to use esnext according to this, writing in javascript instead of typescript, limiting the webpack chunk count to 1, and different ways of importing and compiling wasm from the documentation and online

Terrigenous answered 6/7, 2020 at 12:57 Comment(0)
S
0

I've run into this exact same error, and it actually happened because I was double-loading the WASM file. In my webpack config I had my wasm-pack config:

config.plugin('wasm-pack')
    .use(WasmPackPlugin)
    .init(
      (Plugin) =>
        new Plugin({
          crateDirectory: path.resolve(__dirname, './rust_wasm_code'),
          forceMode: 'release'
        })
    )
    .end()

as well as file-loading code for loading WASM files:

config.module
    .rule('wasm')
    .test(/.wasm$/)
    .use('wasm-loader')
    .loader('wasm-loader')

I fixed the error by removing the second piece of code (and relying on WASM-pack to compile and load).

Spectrochemistry answered 14/7, 2021 at 0:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.