patternjavascriptMajor
Vite library mode: building a reusable package with rollupOptions
Viewed 0 times
Vite 3+
vite library modebuild libexternalize reactrollupOptions externalpublish package vite
Error Messages
Problem
Using Vite to publish a UI component library bundles React (or other peer deps) into the output, massively inflating package size and causing duplicate React instance errors in consumers.
Solution
Enable library mode and externalize peer dependencies so they are not bundled.
// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { resolve } from 'path';
export default defineConfig({
plugins: [react()],
build: {
lib: {
entry: resolve(__dirname, 'src/index.ts'),
name: 'MyLib',
formats: ['es', 'cjs'],
fileName: (format) =>
},
rollupOptions: {
external: ['react', 'react-dom', 'react/jsx-runtime'],
output: {
globals: { react: 'React', 'react-dom': 'ReactDOM' },
},
},
},
});
// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { resolve } from 'path';
export default defineConfig({
plugins: [react()],
build: {
lib: {
entry: resolve(__dirname, 'src/index.ts'),
name: 'MyLib',
formats: ['es', 'cjs'],
fileName: (format) =>
my-lib.${format}.js,},
rollupOptions: {
external: ['react', 'react-dom', 'react/jsx-runtime'],
output: {
globals: { react: 'React', 'react-dom': 'ReactDOM' },
},
},
},
});
Why
In library mode Vite switches to Rollup's bundling pipeline optimised for producing clean ESM/CJS outputs without HTML entry points. Externalizing React prevents the consumer from loading two React copies, which breaks hooks.
Gotchas
- Set 'sideEffects: false' in package.json to allow consumer bundlers to tree-shake your library
- Use the 'exports' field in package.json to map 'import' to ESM output and 'require' to CJS
- CSS imported in the library needs special handling — consider exporting it separately or using CSS-in-JS
- Type declarations must be generated separately (via tsc or vite-plugin-dts)
Context
Building and publishing a component library or utility package using Vite
Revisions (0)
No revisions yet.