初始化器

始于:0.19.0-alpha.1

Trunk 支持介入 WebAssembly 应用程序的初始化过程。默认情况下,此功能未激活,其工作方式与之前的版本相同。

默认过程是 Trunk 注入一个小的 JavaScript 代码片段,该代码片段导入 wasm_bindgen 生成的 JavaScript 加载器,并调用 init 方法。这将获取 WASM blob 并运行它。

这样做的不利之处在于,在此过程中,用户没有任何反馈。无论是加载 WASM 文件需要更长时间,还是出现错误,都没有反馈。

现在可以通过将 data-initializer 设置为 JavaScript 模块文件来介入此过程。此模块文件需要(默认)导出一个函数,该函数返回“initializer”实例。这是一个示例

export default function myInitializer () {
  return {
    onStart: () => {
      // called when the loading starts
    },
    onProgress: ({current, total}) => {
      // the progress while loading, will be called periodically.
      // "current" will contain the number of bytes of the WASM already loaded
      // "total" will either contain the total number of bytes expected for the WASM, or if the server did not provide
      //   the content-length header it will contain 0.
    },
    onComplete: () => {
      // called when the initialization is complete (successfully or failed)
    },
    onSuccess: (wasm) => {
      // called when the initialization is completed successfully, receives the `wasm` instance
    },
    onFailure: (error) => {
      // called when the initialization is completed with an error, receives the `error`
    }
  }
};

有关完整示例,请参阅:https://github.com/trunk-rs/trunk/tree/main/examples/initializer