javascriptvite

Vite bundling common js into a single bundle


I have an old project that's using cjs and we want to switch to vite for bundling all into a iife formatted bundle file.

However vite doesn't seem to bundle cjs modules even though it's stated that it's using the commonjs rollup plugin internally to support cjs.

An example setup:

// src/a.js
function a(chars) {
    console.log('chars', chars);
}

module.exports = a;
// src/index.js
const a = require('./a');

a('hello');

with following config:

// vite.config.js
import { defineConfig } from 'vite';
import { resolve } from 'path';

export default defineConfig({
    build: {
        lib: {
            name: 'bundle',
            entry: resolve(import.meta.dirname, 'src', 'index'),
            formats: ['iife'],
        },
    },
});

results in a single bundle file of:

(function(){"use strict";require("./a")("hello")})();

As you can see nothing of the a.js file is included.

NOTE: when switching the example to esm modules vite properly bundles everything.

How can i enable cjs support in my vite setup to support this? Thank you in advance.


Solution

  • For all that encounter a similar problem, I was able to solve it by adjusting my vite config and just enabling commonjsOptions (setting it to an object didnt work for me):

    // vite.config.js
    import { defineConfig } from 'vite';
    import { resolve } from 'path';
    
    export default defineConfig({
        build: {
            commonjsOptions: true, // this needs to be set to true
            lib: {
                name: 'bundle',
                entry: resolve(import.meta.dirname, 'src', 'index'),
                formats: ['iife'],
            },
        },
    });