试图了解如何通过 webpack 导入 web-assembly 包 [英] Trying to understand how to import web-assembly package via webpack

查看:24
本文介绍了试图了解如何通过 webpack 导入 web-assembly 包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 webpack@4.43.0 上,我正在尝试使用这个 Web 程序集库 https://github.com/vislyhq/stretch 根据文档,我正在从中导入一些类,即

I'm on webpack@4.43.0 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, {});
  }
}

但是,当我尝试使用 webpack 构建它时(不使用任何加载器并且我的 resolve.extensions webpack 配置中有 .wasm)我收到以下错误

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 模块包含在初始块中.这是不允许的,因为 WebAssembly 下载和编译必须异步进行.在您之间的某处添加一个异步拆分点(即 import())入口点和 WebAssembly 模块:

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:

据我所知,我需要对这个模块使用 import(),但是如何让这些导入对我的班级可用?应用程序会失败,因为我们需要等待导入?如果我做这样的事情,我会收到一个错误,说 AllocatorNode 不是构造函数.

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

推荐答案

我能够使用 webpack 5 的最新测试版解决这个问题,方法是在 config 中添加以下实验标志

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

  experiments: {
    asyncWebAssembly: true,
    importAsync: true
  }

这样你就不必担心任何异步 import() 语句

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

这篇关于试图了解如何通过 webpack 导入 web-assembly 包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆