Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can I exclude specific CommonJS modules from being converted to ESM in Vite


Can I exclude specific CommonJS modules from being converted to ESM in Vite


To exclude specific CommonJS modules from being converted to ESM in Vite, you can use the `optimizeDeps` option in your `vite.config.js` file. Here is an example of how to do this:

javascript
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';

export default defineConfig({
  plugins: [
    vue(),
  ],
  optimizeDeps: {
    include: ['node_modules/your-cjs-module'], // Include specific CJS modules
    exclude: ['node_modules/your-cjs-module-that-should-not-be-transformed'], // Exclude specific CJS modules
  },
});

In this example, the `include` option is used to specify the CommonJS modules that should be included in the optimization process. The `exclude` option is used to specify the CommonJS modules that should not be included in the optimization process.

Additional Options

- `esbuildOptions`: This option allows you to specify additional options for the `esbuild` transformer. For example, you can use it to specify the plugins to use for the transformation:
javascript
  optimizeDeps: {
    esbuildOptions: {
      plugins: [require('esbuild-plugin-commonjs')],
    },
  },
  

- `transform`: This option allows you to specify a custom transformer for the CommonJS modules. For example, you can use it to specify a custom transformer that converts CommonJS modules to ESM:

javascript
  optimizeDeps: {
    transform: (code) => {
      // Custom transformer logic here
      return code;
    },
  },
  

Conclusion

By using the `optimizeDeps` option in your `vite.config.js` file, you can control which CommonJS modules are converted to ESM during the development process. This allows you to maintain compatibility with existing projects that use CommonJS while still leveraging the benefits of ESM for new projects.
Citations:
[1] https://github.com/vitejs/vite/discussions/8726
[2] https://www.npmjs.com/package/%40originjs/vite-plugin-commonjs
[3] https://github.com/vitejs/vite/issues/2652
[4] https://www.reddit.com/r/laravel/comments/xebkii/migrate_your_existing_webpackmixjs_to_vite_config/
[5] https://laracasts.com/series/lukes-larabits/episodes/3