Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How does vite-plugin-commonjs handle exclusions for CommonJS modules
    undefined


How does vite-plugin-commonjs handle exclusions for CommonJS modules


The `@originjs/vite-plugin-commonjs` plugin provides a way to exclude specific CommonJS modules from being transformed to ESM during the Vite build process.

Here's how you can use the `exclude` and `include` options to control which CommonJS modules are transformed:

1. Excluding CommonJS modules:
You can use the `exclude` option to specify an array of dependencies that should not be transformed from CommonJS to ESM:

javascript
   import { viteCommonjs } from '@originjs/vite-plugin-commonjs'

   export default {
     plugins: [
       viteCommonjs({
         exclude: ['react-calendar', 'react-date-picker']
       })
     ]
   }
   

In this example, the `react-calendar` and `react-date-picker` dependencies will not be transformed by the plugin.

2. Including specific CommonJS modules:
Alternatively, you can use the `include` option to specify an array of dependencies that should be transformed from CommonJS to ESM:

javascript
   import { viteCommonjs } from '@originjs/vite-plugin-commonjs'

   export default {
     plugins: [
       viteCommonjs({
         include: ['moment', 'lodash']
       })
     ]
   }
   

In this case, only the `moment` and `lodash` dependencies will be transformed, while all other CommonJS dependencies will be left untouched.

3. Excluding CommonJS modules in `optimizeDeps`:
If you have CommonJS modules in your `node_modules` that you want to exclude from the pre-bundling process, you can use the `optimizeDeps.exclude` option in your `vite.config.js` file:

javascript
   import { defineConfig } from 'vite'
   import { esbuildCommonjs } from '@originjs/vite-plugin-commonjs'

   export default defineConfig({
     optimizeDeps: {
       esbuildOptions: {
         plugins: [
           esbuildCommonjs(['react-calendar', 'react-date-picker'])
         ]
       }
     }
   })
   

This will ensure that the `react-calendar` and `react-date-picker` dependencies are not pre-bundled by Vite, and will be handled by the `vite-plugin-commonjs` plugin instead.

By using these options, you can selectively control which CommonJS modules are transformed to ESM, allowing you to maintain compatibility with existing CommonJS dependencies while still benefiting from Vite's performance optimizations.

Citations:
[1] https://www.npmjs.com/package/%40originjs/vite-plugin-commonjs
[2] https://github.com/laravel/vite-plugin/actions
[3] https://laravel.com/docs/11.x/vite
[4] https://github.com/laravel/vite-plugin/blob/1.x/UPGRADE.md
[5] https://vitejs.dev/guide/features