Vite Plugin Top-Level Await

raw JSON →
1.6.0 verified Mon Apr 27 auth: no javascript

A Vite plugin that transforms ES modules using top-level await (TLA) into compatible code for browsers that do not natively support TLA. Version 1.6.0 is current, with a moderate release cadence. It works by rewriting imports and exports to use Promise-based orchestration, handling circular dependencies correctly. Unlike setting build.target to esnext, this plugin retains compatibility with Vite's default browser targets. Supports both ES and IIFE worker formats. Notable alternatives include vite-plugin-top-level-await by Menci (this one) and manualPromise-based polyfilling; this plugin is the most popular and actively maintained for Vite ≥2.8.

error Error: The plugin 'vite:top-level-await' doesn't support CommonJS. Use 'import' instead of 'require'.
cause Using require() to import the plugin,
fix
Change to import statement: import topLevelAwait from 'vite-plugin-top-level-await'
error TypeError: topLevelAwait is not a function
cause Accidentally imported a named export instead of default,
fix
Use default import: import topLevelAwait from 'vite-plugin-top-level-await' (no destructuring)
error Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'vite'
cause Missing Vite peer dependency,
fix
Install vite: npm install -D vite
gotcha Plugin may fail if other plugins transform the bundle before it, as it relies on parsing Rollup's output export statement.
fix Place vite-plugin-top-level-await early in the plugins array, after transformations that modify bundle structure.
gotcha When an TLA dependency is being awaited, accessing its exports will NOT raise an exception (circular dependency handling may be unexpected).
fix Ensure no circular dependencies with top-level await, or design code to handle missing exports.
gotcha Worker IIFE mode requires building worker as ES first then converting, which adds complexity.
fix For Firefox support, use IIFE format and follow the documented pattern for worker instantiation.
npm install vite-plugin-top-level-await
yarn add vite-plugin-top-level-await
pnpm add vite-plugin-top-level-await

Basic Vite config using plugin with default options, plus example of top-level await usage in source code.

// vite.config.js
import { defineConfig } from 'vite';
import topLevelAwait from 'vite-plugin-top-level-await';

export default defineConfig({
  plugins: [
    topLevelAwait({
      promiseExportName: '__tla',
      promiseImportName: i => `__tla_${i}`
    })
  ]
});

// src/main.js - uses top-level await
import { fetchData } from './data.js';
const data = await fetchData();
export { data };