Vite async iife

Vite async iife
typescript
Ethan Jackson

I want to build a single TypeScript file with Vite into a single JavaScript file.

One could easily build an iife by specifying build.lib.formats = ['iife'] in the config, but I would like to compile to an async iife instead. This is so that I can write userscripts.

Answer

I discovered that the vite-plugin-top-level-await plugin automatically wraps code in an async IIFE, to serve its original purpose of allowing top-level await. But, we can easily reuse it for this purpose too.

import { defineConfig } from 'vite'; import topLevelAwait from "vite-plugin-top-level-await"; export default defineConfig({ build: { // ... }, plugins: [ // Wrap in async iife topLevelAwait() ] });

Related Articles