Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 38 ยท Build and Optimization

Vite Library Mode

Build a reusable library with Vite: build.lib, ES and UMD formats, externalizing dependencies, package.json exports, type declarations and publishing checks.

Vite is not only for apps. When you want to publish a package to npm, such as a utility library or a set of UI components, library mode turns Vite's build into a library bundler. Instead of an index.html entry you give it a JavaScript entry file, choose output formats, and decide which dependencies stay outside the bundle.

This lesson walks through a complete setup: config, package.json fields, type declarations and a pre-publish checklist. Real Vite code is read-only; the runnable blocks are stand-ins that test the logic of exports resolution and externalization.

Minimal library config

Suppose your package tiny-math has this entry:

JavaScript
// src/index.js
export function clamp(value, min, max) {
  return Math.min(Math.max(value, min), max);
}
export function lerp(a, b, t) {
  return a + (b - a) * t;
}

The Vite config:

JavaScript
// vite.config.js (real Vite, read-only)
import { defineConfig } from 'vite';
import { resolve } from 'node:path';

export default defineConfig({
  build: {
    lib: {
      entry: resolve(import.meta.dirname, 'src/index.js'),
      name: 'TinyMath',       // global name, only for UMD/IIFE
      fileName: 'tiny-math',  // base name of output files
      formats: ['es', 'cjs'], // defaults: es and umd
    },
    rollupOptions: {
      external: ['react'],    // do not bundle these
    },
  },
});

After vite build the dist folder holds tiny-math.js (ES module) and tiny-math.cjs (CommonJS). Since a library is consumed by other bundlers, Vite does not minify the ES output by default and keeps it readable and tree-shakable.

Formats

Format Use
es Modern bundlers and Node with ESM; supports tree shaking. The most important one
cjs Older Node tooling and require()
umd A script tag in the browser or AMD; needs name
iife A script tag, no module system; needs name

Most new libraries ship es plus cjs. UMD/IIFE are only for people who drop a <script> tag in a page.

Externalize peer dependencies

If your component library uses React and you bundle React into it, users end up with two copies of React and hooks break. Mark framework packages as external and list them as peer dependencies:

JavaScript
// real Vite
rollupOptions: {
  external: ['react', 'react-dom', 'react/jsx-runtime'],
  output: {
    globals: { react: 'React', 'react-dom': 'ReactDOM' }, // names for UMD/IIFE
  },
},
JSON
{
  "peerDependencies": { "react": ">=18", "react-dom": ">=18" }
}

Dependencies listed in dependencies are installed by your users anyway, so they are usually also external. A good rule: externalize everything that is not code you own.

JS Stand-in: externalize or bundle?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

tiny-internal-lib is not listed anywhere, so it would be bundled, which is correct only if it is a build-time dev dependency.

package.json: tell consumers what to load

JSON
{
  "name": "tiny-math",
  "version": "1.0.0",
  "type": "module",
  "files": ["dist"],
  "main": "./dist/tiny-math.cjs",
  "module": "./dist/tiny-math.js",
  "types": "./dist/index.d.ts",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "import": "./dist/tiny-math.js",
      "require": "./dist/tiny-math.cjs"
    },
    "./package.json": "./package.json"
  },
  "sideEffects": false
}
  • exports is the modern entry map. import is used by ESM consumers, require by CommonJS ones. Put types first.
  • files limits what npm publishes.
  • sideEffects: false tells bundlers that unused imports can be dropped, which enables tree shaking. Only set it if your modules truly have no side effects at import time (CSS imports count as side effects).
JS Stand-in: resolving the exports map

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The last line shows an important property: anything not listed in exports cannot be imported by consumers, which protects your internals.

Type declarations

Vite does not generate .d.ts files. For TypeScript libraries, either run tsc --emitDeclarationOnly after the build or use vite-plugin-dts:

JavaScript
// real Vite
import dts from 'vite-plugin-dts';
plugins: [dts({ rollupTypes: true })]

CSS in libraries

If your components import CSS, Vite writes a single style.css next to the JavaScript (set build.cssCodeSplit: true to keep per-chunk CSS). Document that consumers must import it, or inline styles into JS with a plugin like vite-plugin-css-injected-by-js. Note that a CSS import is a side effect, so do not combine blanket "sideEffects": false with CSS imports; use "sideEffects": ["**/*.css"].

Pre-publish checklist

  1. npm run build, then npm pack --dry-run to see exactly which files will be published.
  2. Install the packed tarball in a scratch project and import it from both ESM and CommonJS.
  3. Check that react (or other peers) is not inside your bundle.
  4. Verify the types entry works in a TypeScript project.
  5. Bump the version and publish with npm publish.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which build option turns on library mode?

    build.lib takes entry, name, fileName and formats.
  2. 2. Why mark react as external in a React component library?

    Components must share the host app's React instance, so React is a peer dependency, not part of the bundle.
  3. 3. Which package.json field is the modern, conditional entry map?

    exports maps import paths to files per condition (import, require, types) and hides unexported files.
  4. 4. Does Vite generate TypeScript declaration files for a library?

    Declaration output is not part of Vite's build; add tsc or a plugin.

Summary

  • build.lib builds a package from a JS entry; choose es and usually cjs.
  • Externalize peer and runtime dependencies; list peers in peerDependencies.
  • Describe the package with exports, types, files and an accurate sideEffects.
  • Generate .d.ts files with tsc or vite-plugin-dts.
  • Test the packed tarball before publishing.

Next: Bundle Analysis and Performance