Vite 中文文档 Vite 中文文档
指南
GitHub (opens new window)
指南
GitHub (opens new window)
  • vite

    • 指引
    • 为什么选 Vite
    • 开始
    • 功能
    • 命令行界面
    • 使用插件
    • 依赖预构建
    • 静态资源处理
    • 构建生产版本
    • 部署静态站点
    • 环境变量和模式
    • 服务端渲染
    • 后端集成
    • 与其他工具比较
    • 故障排除
    • 从 v3 迁移
  • API

  • 配置参考

  • vite

  • API

  • 配置参考

vite-plugin-wasm


Add WebAssembly ESM integration (aka. Webpack's asyncWebAssembly ) to Vite and support wasm-pack generated modules.

Installation


Now this plugin supports both Vite 2.x and 3.x. Just install it:

  1. ``` shell
  2. yarn add -D vite-plugin-wasm
  3. ```

Usage


You also need the vite-plugin-top-level-await plugin unless you target very modern browsers only (i.e. set build.target to esnext ).

  1. ``` ts
  2. import wasm from "vite-plugin-wasm";
  3. import topLevelAwait from "vite-plugin-top-level-await";

  4. export default defineConfig({
  5.   plugins: [
  6.     wasm(),
  7.     topLevelAwait()
  8.   ]
  9. });
  10. ```

If you are getting ESBuild errors of WASM files (In the format No loader is configured for ".wasm" files: node_modules/somepackage/somefile.wasm ) with Vite < 3.0.3, please upgrade your Vite to >= 3.0.3 or upgrade this plugin to >= 3.1.0. A workaround is adding the corresponding imported module within node_modules to optimizeDeps.exclude, e.g.:

  1. ``` ts
  2. export default defineConfig({
  3.   optimizeDeps: {
  4.     exclude: [
  5.       "@syntect/wasm"
  6.     ]
  7.   }
  8. });
  9. ```

Web Worker


To use this plugin in Web Workers. Add it (and vite-plugin-top-level-await if necessary) to worker.plugins. To support Firefox, don't use ES workers. leave worker.format default and use vite-plugin-top-level-await >= 1.3.0:

  1. ``` ts
  2. export default defineConfig({
  3.   plugins: [
  4.     wasm(),
  5.     topLevelAwait()
  6.   ],
  7.   worker: {
  8.     // Not needed with vite-plugin-top-level-await >= 1.3.0
  9.     // format: "es",
  10.     plugins: [
  11.       wasm(),
  12.       topLevelAwait()
  13.     ]
  14.   }
  15. });
  16. ```

Notes


TypeScript typing is broken. Since we can't declare a module with Record<string, any> as its named export map. Your import ... from "./module.wasm"; will still got Vite's bulit-in typing, but the transformed code is fine. So just use an asterisk import import * as wasmModule from "./module.wasm" and type assertion (you have typing for your WASM files, right?).
Last Updated: 2023-05-23 11:11:51