Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to understand how to import web-assembly package via webpack

I'm on [email protected] and am trying to use this web assembly library https://github.com/vislyhq/stretch As per docs I am importing some classes from it i.e.

import { Allocator, Node } from 'stretch-layout';

class Base {
  public layoutNode;

  public constructor() {
    this.layoutNode = new Node(allocator, {});
  }
}

However when I am trying to build it with webpack (not using any loaders and I have .wasm in my resolve.extensions webpack config) I am getting following error

WebAssembly module is included in initial chunk. This is not allowed, because WebAssembly download and compilation must happen asynchronous. Add an async splitpoint (i. e. import()) somewhere between your entrypoint and the WebAssembly module:

To my understanding I need to use import() for this module, but how do I make these imports available to my class? Application will fail since we need to await that import? If I do something like this I get an error saying that Allocator and Node are not constructors.

let Allocator: any = null;
let Node: any = null;

import('stretch-layout').then(module => {
  Allocator = module.Allocator;
  Node = module.Node;
});
like image 327
Ilja Avatar asked Jul 09 '20 14:07

Ilja


People also ask

How does webpack import work?

When webpack processes your application, it internally builds a dependency graph from one or more entry points and then combines every module your project needs into one or more bundles, which are static assets to serve your content from.


1 Answers

I was able to solve this using latest beta of webpack 5, by adding following experimental flags to config

  experiments: {
    asyncWebAssembly: true,
    importAsync: true
  }

this way you don't have to worry about any async import() statements at all

like image 125
Ilja Avatar answered Oct 25 '22 22:10

Ilja