TExcelTAD
Home › Vite › Vite Library Mode

Vite Library Mode

Vite isn't only for apps. With library mode you can build a reusable package — a set of utilities, a UI component, a web component — and publish it to npm. The output is JavaScript files meant to be imported by other projects, not an index.html site.

App build vs library build

App (vite build) Library (build.lib)
Entry index.html A JS/TS file (e.g. src/index.ts)
Output names Hashed (index-C3k9pQ2x.js) Stable (my-lib.js)
Dependencies Bundled in Usually externalized (left as imports)
Formats ES modules for browsers es, umd, cjs, iife
public/ Copied Not copied

A tiny library

ts
// src/index.ts
export function slugify(text: string): string {
  return text
    .toLowerCase()
    .normalize('NFD')
    .replace(/[̀-ͯ]/g, '')
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/(^-|-$)/g, '');
}

export function truncate(text: string, max: number): string {
  return text.length <= max ? text : text.slice(0, max - 1) + '…';
}

Let's make sure the logic works (same code, without types):

js · try it yourself
function slugify(text) {
  return text
    .toLowerCase()
    .normalize('NFD')
    .replace(/[̀-ͯ]/g, '')
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/(^-|-$)/g, '');
}
function truncate(text, max) {
  return text.length <= max ? text : text.slice(0, max - 1) + '…';
}

console.log(slugify('Hello Vite Library Mode!'));
console.log(slugify('  Xin chào Việt Nam  '));
console.log(truncate('A fast build tool for the web', 12));
hello-vite-library-mode
xin-chao-viet-nam
A fast buil…

The config

ts
// vite.config.ts
import { defineConfig } from 'vite';
import { resolve } from 'node:path';

export default defineConfig({
  build: {
    lib: {
      entry: resolve(import.meta.dirname, 'src/index.ts'),
      name: 'TextKit',          // global variable name for the UMD/IIFE build
      fileName: 'text-kit',     // -> text-kit.js, text-kit.umd.cjs
      // formats: ['es', 'umd'] is the default for a single entry
    },
    rolldownOptions: {
      // don't bundle peer dependencies into the library
      external: ['vue', 'react', 'react-dom'],
      output: {
        globals: { vue: 'Vue', react: 'React', 'react-dom': 'ReactDOM' },
      },
    },
  },
});
bash · try it yourself
npx vite build
vite v8.3.4 building client environment for production...
✓ 1 modules transformed.
dist/text-kit.js      0.31 kB │ gzip: 0.23 kB
dist/text-kit.umd.cjs  0.58 kB │ gzip: 0.37 kB
✓ built in 41ms

Externalize your dependencies

If your library imports vue, the app using it already has Vue. Bundling a second copy would double the size and can break things (two Vue instances, two React instances…). List such packages in external. A common trick is to externalize everything in dependencies and peerDependencies:

js · try it yourself
const pkg = {
  dependencies: { 'date-fns': '^4.1.0' },
  peerDependencies: { vue: '^3.5.0' },
};
const deps = [...Object.keys(pkg.dependencies), ...Object.keys(pkg.peerDependencies)];
const external = (id) => deps.some((d) => id === d || id.startsWith(d + '/'));

for (const id of ['vue', 'date-fns/format', './utils.js', 'lodash-es']) {
  console.log(id.padEnd(16), external(id) ? 'external (stays an import)' : 'bundled');
}
vue              external (stays an import)
date-fns/format  external (stays an import)
./utils.js       bundled
lodash-es        bundled

package.json for publishing

json
{
  "name": "text-kit",
  "version": "1.0.0",
  "type": "module",
  "files": ["dist"],
  "main": "./dist/text-kit.umd.cjs",
  "module": "./dist/text-kit.js",
  "types": "./dist/index.d.ts",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "import": "./dist/text-kit.js",
      "require": "./dist/text-kit.umd.cjs"
    }
  },
  "sideEffects": false,
  "scripts": {
    "build": "vite build && tsc --emitDeclarationOnly --declaration --outDir dist"
  }
}
Field Purpose
exports Modern entry map; bundlers and Node pick import or require
main / module Fallbacks for older tools
types TypeScript declarations (Vite doesn't emit .d.ts; use tsc or vite-plugin-dts)
files Only publish dist/
sideEffects: false Lets consumers tree-shake your library

Multiple entry points

ts
lib: {
  entry: {
    index: resolve(import.meta.dirname, 'src/index.ts'),
    string: resolve(import.meta.dirname, 'src/string.ts'),
  },
  formats: ['es', 'cjs'], // umd/iife don't support multiple entries
},

Consumers can then import { slugify } from 'text-kit/string' (add matching exports entries).

CSS in libraries

If the library imports CSS, Vite emits a separate CSS file (named by build.lib.cssFileName or the package name). Consumers import it explicitly, e.g. import 'text-kit/style.css', or you can inline it with ?inline for web components.

Using the UMD build without a bundler

The UMD file exposes a global (the name option). Here is a page that defines such a global the way the UMD wrapper does, and uses it from a classic script:

html · try it yourself
<!doctype html>
<html>
  <body style="font-family: system-ui">
    <script>
      // what text-kit.umd.cjs does when there is no module system: attach to window
      (function (global, factory) {
        global.TextKit = factory();
      })(this, function () {
        return {
          slugify: (t) => t.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/(^-|-$)/g, ''),
        };
      });
    </script>
    <p>Slug: <strong id="out"></strong></p>
    <script>
      document.getElementById('out').textContent = TextKit.slugify('My First Vite Library');
    </script>
  </body>
</html>

Tip: Test your package locally before publishing with npm pack and install the generated .tgz in another project — it catches missing files and broken exports.

Test yourself

What is the entry of a library-mode build?

  1. index.html
  2. A JS/TS file set in build.lib.entry
  3. package.json
  4. public/index.js

Why mark react as external in a React component library?

  1. To make the build fail faster
  2. So the consuming app's own React is used instead of bundling a second copy
  3. Because React is not on npm
  4. To enable UMD

Which tool produces .d.ts files for a TypeScript library built with Vite?

  1. Vite itself, automatically
  2. tsc (or a plugin such as vite-plugin-dts)
  3. Oxc minifier
  4. npm publish