Skip to content

Resolving Vite's CJS Node API Deprecation Warning

Problem Statement

When running vite build in Vite 5, you may encounter this warning:

bash
The CJS build of Vite's Node API is deprecated. See https://vitejs.dev/guide/troubleshooting.html#vite-cjs-node-api-deprecated for more details.

This warning indicates you're using Vite's legacy CommonJS (CJS) API instead of the newer ESM (ECMAScript Modules) system. Vite deprecated its CJS Node API starting with version 5 to embrace modern JavaScript standards. Users attempting to follow troubleshooting instructions by adding VITE_CJS_TRACE=true may encounter errors like:

bash
'VITE_CJS_TRACE' is not recognized as an internal or external command

This happens due to platform-specific differences in setting environment variables.

1. Migrate to ESM Format (Preferred Solution)

The most robust solution involves converting your project to use ES Modules:

json
{
  "type": "module"  // Add this property
}
ts
// Rename your configuration file
vite.config.ts → vite.config.mts
js
// Rename your configuration file
vite.config.js → vite.config.mjs

Explanation:

  • Setting "type": "module" in package.json forces Node.js to interpret .js files as ES modules
  • File extensions .mjs (JavaScript modules) and .mts (TypeScript modules) explicitly declare module format
  • This aligns with Vite's recommended approach and future development direction

2. Temporary Workaround: Trace Warning Source

If you need to identify what's triggering the warning before migrating:

Platform-Specific Implementation

Environment variables are set differently on Unix-like systems vs. Windows

json
"scripts": {
  "build": "set \"VITE_CJS_TRACE=true\" && vite build"
}
json
"scripts": {
  "build": "VITE_CJS_TRACE=true vite build"
}

Explanation:

  • Windows requires set command to define environment variables
  • Unix-like systems support direct variable declaration before commands
  • Running with VITE_CJS_TRACE=true will output a stack trace pinpointing the problematic module

Why Vite Deprecates CJS

Vite has shifted focus entirely to ES Modules because:

  1. ESM is the modern JavaScript standard supported by browsers
  2. Enables better tree-shaking and optimization
  3. Simplifies Vite's internal architecture
  4. Supports top-level await and other modern features
  5. Aligns with the ecosystem shift towards ESM

Migration Recommendation

Although temporary workarounds exist, converting to ESM ensures compatibility with future Vite versions and leverages modern JavaScript capabilities. Most modern libraries and frameworks have adopted ESM conventions.

Verifying Your Solution

After making changes, confirm the warning is resolved by:

  1. Deleting node_modules and lockfile
  2. Running npm install or yarn install
  3. Executing your build command:
bash
npm run build

Additional Resources

By migrating to ESM, you ensure compatibility with Vite's future versions and modern JavaScript ecosystem standards.