This package, `vite-plugin-commonjs`, provides a pure JavaScript implementation to process CommonJS modules within a Vite build. It enables Vite to correctly handle `require` statements, `module.exports`, and `exports` patterns often found in legacy or Node.js-focused libraries that haven't transitioned to ESM. The current stable version is 0.10.4, with frequent minor updates indicating active development and maintenance, often incorporating community contributions. Key differentiators include robust support for dynamic `require` expressions, similar to Webpack's behavior, and explicit handling for `node_modules` and aliases, which are often problematic when migrating CommonJS-heavy projects to Vite's ESM-first approach. It ships with TypeScript types for improved development experience.
npm install vite-plugin-commonjsVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to integrate `vite-plugin-commonjs` into a Vite project's configuration, showing basic options for filtering modules, handling dynamic `require`, and advanced import rules.
Modify your plugin configuration: `commonjs({ filter: (id) => id.includes('node_modules/your-cjs-lib') || !id.includes('node_modules') })`.Consult the `CHANGELOG.md` on the GitHub repository for specific migration steps and updated configuration options when upgrading to a new minor version.
For problematic dependencies, consider using Vite's `optimizeDeps.exclude` to let Vite pre-bundle them without plugin intervention, or manually inspect the transformed output to pinpoint and address the specific issue.
Ensure `vite-plugin-commonjs` is correctly installed, configured in `vite.config.js`, and that the file containing the `require` statement is not inadvertently excluded by the plugin's `filter` option or Vite's build process. Restart Vite's development server.
If the CJS module uses `module.exports = value`, try `import value from 'module-name'`. If it uses `exports.foo = value`, try `import { foo } from 'module-name'`. If issues persist, check the `advanced.importRules` option.Ensure the `dynamic` option is enabled in the plugin configuration, especially `dynamic.loose: true` for broader compatibility. Verify that all potential paths for dynamic `require` are accessible and resolvable by Vite.