How to wrap Vite build in IIFE and still have all the dependencies bundled into a single file?

Viewed 25

I'm building a chrome extension using Vite as my build tool. The main problem is during minification and mangling there are a lot of global variables created. After injecting my script to the page they conflict with already defined variables on window object.

I imagine the perfect solution would be to have my entire script wrapped in IIFE. I tried using esbuild.format = 'iife'. The resulting build is in fact wrapped in IIFE, however all the imports are not inlined. Instead resulting script is like 15 lines long with a bunch of require statements, which obviously does not work in the browser.

This is my config file:

export default defineConfig({
  plugins: [
    vue(),
  ],
  esbuild: {
    format: 'iife',
  },
  build: {
    emptyOutDir: false,
    rollupOptions: {
      input: resolve(__dirname, './src/web/index.ts'),
      output: {
        dir: resolve(__dirname, './dist'),
        entryFileNames: 'web.js',
        assetFileNames: 'style.css',
      },
    },
  },
  resolve: {
    alias: {
      '@': resolve(__dirname, './src'),
    },
  },
});

I'm currently using this hack so to say to wrap my build in IIFE (for this I removed the esbuild.format option).

0 Answers
Related