vite

Vite async iife


I am writing a userscript in TypeScript that I want to compile with Vite.

Everything needs to be encapsulated in an iife so that the userscript can run self-contained.

If I weren't using top-level await, I could set build.lib.formats = ['iife'] to have it auto-generate an iife.

Since I am using top-level await, how do I make it build an async iife instead?


Solution

  • 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()
        ]
    });