vite-plugin-cjs2esm

raw JSON →
1.0.10 verified Mon Apr 27 auth: no javascript

Vite plugin that transforms CommonJS modules to ESModules during development, enabling compatibility with Vite's native ESM dev server. As of v1.0.10, it supports static require, dynamic require, and exports conversion. It provides both a Vite plugin for transformation and an esbuild plugin for optimizeDeps. Key differentiator: specifically targets Vite dev mode, unlike general CJS-to-ESM tools. Release cadence is low. Requires Node >=14.18.0.

error Error: ESM integration problem: Could not find plugin function 'vitePlugin'
cause Incorrect import: imported { vitePlugin } instead of default import.
fix
Use: import viteCjsToEsmPlugin from 'vite-plugin-cjs2esm'; then viteCjsToEsmPlugin.vitePlugin()
error Module not found: Error: Can't resolve 'vite-plugin-cjs2esm'
cause Package not installed as dev dependency.
fix
Run: npm install vite-plugin-cjs2esm --save-dev
error Cannot find module './foo' when using dynamic require with import()
cause The dynamic require transformation changes synchronous require to async import(), but the dynamic module path may not be resolved correctly.
fix
Ensure dynamic paths are correctly formatted; test with explicit paths or adjust filter option.
gotcha The plugin transforms require() calls only in development mode; production builds are handled by Vite's default rollup/bundle process. Do not expect CJS transformations in production builds.
fix Ensure production builds properly handle CJS dependencies via Vite's pre-bundling and rollup config.
gotcha dynamic require() calls are converted to dynamic import(). The return value becomes a Promise, which may break synchronous code expecting a direct module value.
fix Refactor synchronous code that uses dynamic require to handle asynchronous import() with .then() or await.
deprecated If used with Vite 5+, the plugin may conflict with Vite's internal CJS handling; test compatibility.
fix Check that the plugin works with your Vite version; consider using Vite's built-in pre-bundling or other plugins.
npm install vite-plugin-cjs2esm
yarn add vite-plugin-cjs2esm
pnpm add vite-plugin-cjs2esm

Configures Vite to convert CommonJS modules to ESM during development using the plugin and its esbuild counterpart.

import { defineConfig } from 'vite';
import viteCjsToEsmPlugin from 'vite-plugin-cjs2esm';

export default defineConfig({
  plugins: [viteCjsToEsmPlugin.vitePlugin()],
  optimizeDeps: {
    esbuildOptions: {
      plugins: [viteCjsToEsmPlugin.esbuildPlugin()]
    }
  }
});