乐闻世界logo
搜索文章和话题

How to set multiple output when build lib with vite

1个答案

1

When building a library with Vite, it is crucial to consider the output format and compatibility issues. Vite supports building libraries in various formats, including ESM, CommonJS, and others. We can configure the build options in Vite to set up multiple outputs.

The following provides specific steps and examples demonstrating how to configure multiple output formats for a library using Vite:

Step 1: Initialize the Project

First, ensure that you have Node.js and Vite installed. Then, run the following command to create a new Vite project:

bash
npm create vite@latest my-lib --template vanilla cd my-lib npm install

Step 2: Configure Vite

In the Vite configuration file vite.config.js, configure the build options to specify the output format. The following is an example configuration for multiple output formats:

javascript
import { defineConfig } from 'vite'; export default defineConfig({ build: { // Library mode configuration lib: { entry: './src/index.js', // Specify entry file name: 'MyLib', // Library's global variable name (for UMD/IIFE format) fileName: (format) => `my-lib.${format}.js` // Output file name format }, // Output format configuration rollupOptions: { // Ensure externalization of dependencies you don't want to bundle into the library external: ['vue'], output: [ { format: 'es', // ESM format dir: 'dist/es', sourcemap: true // Whether to generate source maps }, { format: 'cjs', // CommonJS format dir: 'dist/cjs', sourcemap: true }, { format: 'umd', // UMD format dir: 'dist/umd', sourcemap: true, globals: { vue: 'Vue' } } ] } } });

Step 3: Build the Library

After configuration, run the following command to build the library:

bash
npm run build

This command generates multiple subdirectories (es, cjs, umd) under the dist directory based on your configuration, each containing the corresponding build files.

Example

Suppose your library depends on Vue, and you want users to utilize it across different environments (e.g., via ES modules, CommonJS, or directly in the browser through global variables). With this configuration, you can generate files in three formats, allowing users to select the appropriate format based on their project setup. This approach not only enhances the library's usability but also improves its compatibility across various environments.

2024年8月25日 15:30 回复

你的答案