Vite

Packaging a React component library with Vite

Build a React and TypeScript package in Vite library mode, expose ESM, CommonJS-compatible output, types, and CSS, then inspect the npm tarball.

Packaging a React component library with Vite

An application can own its copy of React and its entry HTML. A shared component package has different responsibilities. I used Vite library mode to build JavaScript, declarations, and CSS that another application can import consistently.

Choosing the package’s entry and formats

Application builds usually start at index.html and can name chunks with hashes because the HTML refers to them. A library starts at a module such as src/index.ts. Consumers need stable entry points, compatible output formats, and declarations that match the public API.

flowchart LR
    subgraph Source["Library source"]
        TS["src/index.ts"]
        Comp["src/components/*.tsx"]
        Hooks["src/hooks/*.ts"]
        TS --> Comp
        TS --> Hooks
    end
    subgraph ViteBuild["Vite build.lib & Plugins"]
        Rollup["Rollup"]
        DtsPlugin["vite-plugin-dts"]
    end
    subgraph Artifacts["Published output"]
        ESM["dist/my-design-system.js (ESM)"]
        CJS["dist/my-design-system.umd.cjs (CJS/UMD)"]
        CSS["dist/style.css"]
        DTS["dist/**/*.d.ts (Type declarations)"]
    end
    Comp --> Rollup
    Hooks --> Rollup
    TS --> DtsPlugin
    Rollup --> ESM
    Rollup --> CJS
    Rollup --> CSS
    DtsPlugin --> DTS

I configured the example to emit ESM and a UMD file with a .cjs extension for the CommonJS entry. Choose both only when the consumers need both. Each new format increases the number of package paths that need testing. Excluding React and React DOM from the library bundle lets the consumer provide the shared Runtime. Bundling a duplicate React instance can trigger invalid hook calls or cause a provider and consumer to use different contexts.

Configuring build.lib and writing the public surface

build.lib selects the TypeScript entry and output formats. The sample also uses vite-plugin-dts to emit declaration files. It keeps React external and declares the runtime global names used by the UMD build.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import dts from 'vite-plugin-dts';
import { resolve } from 'path';

export default defineConfig({
  plugins: [
    react(),
    // Emit TypeScript declaration files
    dts({
      tsconfigPath: './tsconfig.json',
      outDir: 'dist',
      insertTypesEntry: true,
      rollupTypes: false
    })
  ],
  build: {
    // Library-mode setup
    lib: {
      entry: resolve(__dirname, 'src/index.ts'),
      name: 'NamjuDesignSystem', // Global name for the UMD output
      formats: ['es', 'umd'],
      fileName: (format) => `my-design-system.${format === 'es' ? 'js' : 'umd.cjs'}`
    },
    rollupOptions: {
      // Keep dependencies provided by the consuming application external
      external: ['react', 'react-dom', 'react/jsx-runtime'],
      output: {
        // Map external dependencies to UMD globals
        globals: {
          react: 'React',
          'react-dom': 'ReactDOM',
          'react/jsx-runtime': 'jsxRuntime'
        },
        // Use stable asset names
        assetFileNames: (assetInfo) => {
          if (assetInfo.name === 'style.css') return 'style.css';
          return assetInfo.name || 'asset';
        }
      }
    },
    // Generate source maps for debugging
    sourcemap: true,
    // Empty the output directory
    emptyOutDir: true
  }
});

The example library exports a button and a modal hook. Export those symbols through one public entry rather than making consumers reach into the source directory.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// src/components/Button.tsx
import React from 'react';
import './Button.css';

export interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
  variant?: 'primary' | 'secondary' | 'danger';
  size?: 'sm' | 'md' | 'lg';
}

export const Button: React.FC<ButtonProps> = ({
  variant = 'primary',
  size = 'md',
  children,
  className = '',
  ...props
}) => {
  return (
    <button
      className={`nds-button nds-button--${variant} nds-button--${size} ${className}`}
      {...props}
    >
      {children}
    </button>
  );
};
1
2
3
4
5
6
7
8
9
// src/index.ts
// Public component entry point
export { Button } from './components/Button';
export type { ButtonProps } from './components/Button';

export { Modal } from './components/Modal';
export type { ModalProps } from './components/Modal';

export { useModal } from './hooks/useModal';

Run the configured build as you would from CI.

1
2
# Build the library
pnpm build

Vite library build outputs for JavaScript, CSS, and declarations Figure 1. The captured build writes named library outputs into dist.

The project expects my-design-system.js, my-design-system.umd.cjs, style.css, and declaration files. Check the output directly if format or plugin configuration changes. A mismatch between the generated filenames and the exports map produces a package that builds successfully but cannot be imported.

Declaring exports and peer dependencies

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// package.json
{
  "name": "@namju/design-system",
  "version": "1.0.0",
  "description": "A shared React design system",
  "type": "module",
  "main": "./dist/my-design-system.umd.cjs",
  "module": "./dist/my-design-system.js",
  "types": "./dist/index.d.ts",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "import": "./dist/my-design-system.js",
      "require": "./dist/my-design-system.umd.cjs"
    },
    "./style.css": "./dist/style.css"
  },
  "files": [
    "dist",
    "README.md",
    "LICENSE"
  ],
  "sideEffects": [
    "**/*.css"
  ],
  "peerDependencies": {
    "react": "^18.0.0 || ^19.0.0",
    "react-dom": "^18.0.0 || ^19.0.0"
  },
  "devDependencies": {
    "@types/react": "^18.3.0",
    "@types/react-dom": "^18.3.0",
    "@vitejs/plugin-react": "^4.3.0",
    "typescript": "^5.6.0",
    "vite": "^5.4.8",
    "vite-plugin-dts": "^4.2.1"
  }
}

The exports map advertises separate entry files for import and require. Put types first in the relevant declaration condition, and make packages that need distinct module-format declarations resolve them correctly. The CSS subpath makes the stylesheet a supported public import without depending on the internal directory shape.

files restricts package contents to the build output and necessary documentation. The sideEffects array tells the consuming bundler to retain styles when it removes unused JavaScript. Declaring React as a peer dependency communicates that the consuming app owns its runtime version.

Check the peer version range against the React versions actually supported by the components. Use dev dependencies to keep local and CI tests runnable, and make sure the bundler’s external configuration also reflects that decision.

Inspecting what npm will publish

npm pack --dry-run lists the tarball contents, size, and integrity metadata without writing the archive. It is a useful last check after the package has been built.

1
2
# Inspect the tarball before publishing
npm pack --dry-run

npm pack dry-run output for the component package Figure 2. The dry run lists the entries and type files that would be published.

Check dist/index.d.ts, both JavaScript formats, and the stylesheet in the listing. Keep repository configuration and unpublished source out of the public archive. If your release depends on a prepack step, use the same release command locally or in CI. A successful vite build alone does not prove the tarball contains everything.

Checking a consuming application

Import the stylesheet once at the application boundary.

1
2
3
// Consuming application entry (main.tsx)
import '@namju/design-system/style.css';
import { Button } from '@namju/design-system';

An injected stylesheet can simplify client-only use, but runtime style injection can make the first SSR paint unstyled. A separate CSS export lets a consuming framework include the stylesheet in its loading and rendering strategy.

For local iteration I can link the package into a sample app. Link behavior depends on the package-manager version and lockfile rules. Install an actual packed tarball into a clean consumer before publishing to verify the resolution path an external project will use.

1
2
3
4
5
6
7
# 1. Register the library link
cd packages/design-system
pnpm link --global

# 2. Link the package in the sample application
cd apps/demo-app
pnpm link --global @namju/design-system
  • Test ESM import and CommonJS require in matching consumers.
  • Run a TypeScript check in the consuming app to validate the published types.
  • Confirm that styling survives tree shaking and that imports use one React runtime.
  • Inspect the packed tarball before publishing.
Next Generation Frontend Tooling
This post is licensed under CC BY 4.0 by the author.