Vite is a modern build tool that focuses on serving development builds with fast hot-reload capabilities. It primarily targets modern ESM (ECMAScript Modules) and doesn't natively support transforming ESM to CommonJS for Node.js. However, you can use a plugin called @rollup/plugin-commonjs to achieve this transformation when building with Vite.

Here's how you can use Vite and @rollup/plugin-commonjs to build ESM to CommonJS, including Node.js core modules like stream and path:

  1. Install Dependencies:

First, install the required dependencies:

bash
npm install vite @rollup/plugin-commonjs --save-dev
  1. Create a Vite Config File:

Next, create a Vite config file named vite.config.js in the root of your project:

javascript
// vite.config.js import { defineConfig } from 'vite'; import commonjs from '@rollup/plugin-commonjs'; export default defineConfig({ build: { rollupOptions: { plugins: [ commonjs({ include: /node_modules/, namedExports: { // Specify named exports for specific modules if necessary // For example: // 'node_modules/some-library/index.js': ['exportedFunction'], }, }), ], }, }, });

In this config file, we are specifying the @rollup/plugin-commonjs plugin to be used during the build process. We use the include option to include the node_modules folder, ensuring that core Node.js modules like stream and path are processed by the plugin.

  1. Build the Project:

To build your project with Vite and transform ESM to CommonJS, run the following command:

bash
npx vite build

This will build your project and output the CommonJS files to the dist folder.

Please note that while using @rollup/plugin-commonjs allows you to convert ESM to CommonJS, Vite is primarily designed for modern ESM builds and may not handle CommonJS-based projects as efficiently as other build tools like webpack. If you have a complex CommonJS-based project, you might consider using webpack with appropriate configuration for a more seamless experience.

Have questions or queries?
Get in Touch