Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 38 ยท Projects and Practice

Project: A Component Library

Build and publish a small UI component library with Vite library mode: project layout, design tokens, components, build config, exports, tests and a release checklist.

In this project you build tiny-ui, a small component library with a button, a badge and a set of design tokens, and package it with Vite's library mode. You will practice almost everything from the build chapters: build.lib, externals, exports, type declarations, tests and a pre-publish check.

The project files are real and read-only because Vite and npm are not available in our runners. The design-token logic and the packaging checks are runnable stand-ins, so you can verify the parts that are plain JavaScript. Related lessons: Library Mode, Testing with Vitest and Bundle Analysis and Performance.

The goal

A consumer should be able to write:

JSX
import { Button, Badge } from 'tiny-ui';
import 'tiny-ui/style.css';

<Button variant="primary" onClick={save}>Save</Button>
<Badge tone="success">Paid</Badge>

Requirements: ES and CommonJS builds, React as a peer dependency (not bundled), CSS in a single file, TypeScript types, tests, and a tree-shakable output.

Project layout

Text
tiny-ui/
  package.json
  vite.config.ts
  tsconfig.json
  src/
    index.ts
    tokens.ts
    Button.tsx
    Badge.tsx
    styles.css
    Button.test.tsx

Step 1: design tokens

Keep colors and spacing in one place, then generate CSS custom properties from them. This is plain TypeScript with no dependencies, so we can run the logic here.

TypeScript
// src/tokens.ts (real project, read-only)
export const tokens = {
  color: { primary: '#2563eb', success: '#16a34a', danger: '#dc2626', text: '#111827' },
  space: { sm: '4px', md: '8px', lg: '16px' },
  radius: { md: '6px' },
} as const;

export function toCssVariables(t: Record<string, Record<string, string>>): string {
  const lines: string[] = [];
  for (const [group, values] of Object.entries(t)) {
    for (const [name, value] of Object.entries(values)) {
      lines.push(`  --tiny-${group}-${name}: ${value};`);
    }
  }
  return `:root {\n${lines.join('\n')}\n}`;
}
JS Run the token generator

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

No output.

Step 2: components

TSX
// src/Button.tsx (real project, read-only)
import type { ButtonHTMLAttributes } from 'react';
import './styles.css';

export interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
  variant?: 'primary' | 'danger' | 'ghost';
}

export function Button({ variant = 'primary', className = '', ...rest }: ButtonProps) {
  return <button className={`tiny-button tiny-button--${variant} ${className}`.trim()} {...rest} />;
}
TSX
// src/Badge.tsx
import './styles.css';

export function Badge({ tone = 'neutral', children }: { tone?: 'neutral' | 'success'; children: React.ReactNode }) {
  return <span className={`tiny-badge tiny-badge--${tone}`}>{children}</span>;
}
TypeScript
// src/index.ts: the public API; anything not exported here is private
export { Button } from './Button';
export type { ButtonProps } from './Button';
export { Badge } from './Badge';
export { tokens } from './tokens';

Keep the public API small. Every export is a promise you must keep in future versions.

Step 3: the build

TypeScript
// vite.config.ts (real project, read-only)
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import dts from 'vite-plugin-dts';
import { resolve } from 'node:path';

export default defineConfig({
  plugins: [react(), dts({ rollupTypes: true, tsconfigPath: './tsconfig.json' })],
  build: {
    lib: {
      entry: resolve(import.meta.dirname, 'src/index.ts'),
      formats: ['es', 'cjs'],
      fileName: (format) => `tiny-ui.${format === 'es' ? 'js' : 'cjs'}`,
    },
    rollupOptions: {
      external: ['react', 'react-dom', 'react/jsx-runtime'],
    },
    cssCodeSplit: false, // one dist/tiny-ui.css (named style.css in older versions)
    sourcemap: true,
  },
});

The key detail is react/jsx-runtime in external. With the automatic JSX transform, compiled components import react/jsx-runtime; if you forget it, a copy of the JSX runtime gets bundled.

Step 4: package.json

JSON
{
  "name": "tiny-ui",
  "version": "0.1.0",
  "type": "module",
  "files": ["dist"],
  "main": "./dist/tiny-ui.cjs",
  "module": "./dist/tiny-ui.js",
  "types": "./dist/index.d.ts",
  "exports": {
    ".": {
      "types": "./dist/index.d.ts",
      "import": "./dist/tiny-ui.js",
      "require": "./dist/tiny-ui.cjs"
    },
    "./style.css": "./dist/style.css"
  },
  "sideEffects": ["**/*.css"],
  "peerDependencies": { "react": ">=18", "react-dom": ">=18" },
  "devDependencies": { }
}

Two traps: sideEffects must list CSS or bundlers will drop the style import, and the ./style.css export is required, or consumers cannot import it once exports is defined.

Step 5: a test

TSX
// src/Button.test.tsx (real Vitest, read-only)
// @vitest-environment jsdom
import { render, screen } from '@testing-library/react';
import { test, expect } from 'vitest';
import { Button } from './Button';

test('applies the variant class', () => {
  render(<Button variant="danger">Delete</Button>);
  expect(screen.getByRole('button', { name: 'Delete' })).toHaveClass('tiny-button--danger');
});

Step 6: verify the package with a script

Before publishing, check the built package against rules. This stand-in runs those checks on a package description; in the real project you would read package.json and the dist listing from disk.

JS Stand-in: pre-publish checks

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

No output.

Step 7: try it before you publish

Terminal
npm run build
npm pack                       # creates tiny-ui-0.1.0.tgz
# in a scratch React app:
npm install ../tiny-ui/tiny-ui-0.1.0.tgz

Import it from an ESM app and from a require script, confirm the CSS loads and that only one copy of React is installed (npm ls react). Then npm publish.

Extensions to try

  • Add a Modal component and lazy-load it behind a separate entry (tiny-ui/modal) with an exports subpath.
  • Publish a Storybook or a small docs site built with Vite.
  • Add a size budget for the library (see the budget idea in Bundle Analysis and Performance).
  • Add Changesets for versioning and automated release notes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why include react/jsx-runtime in rollupOptions.external?

    The automatic JSX transform imports react/jsx-runtime. It must come from the host app's React.
  2. 2. Why list CSS in sideEffects?

    A CSS import has no exports, so without a side effects flag a bundler may drop it.
  3. 3. What does npm pack let you do?

    You can install the tarball in a scratch project to test exactly what users would get.
  4. 4. Why keep the public API in src/index.ts small?

    Unexported internals can change freely; exported names cannot without a breaking release.

Summary

  • You built tokens, two components, a library build, an exports map, a test and a packaging check.
  • Externalize React and react/jsx-runtime; declare peers.
  • Export the CSS explicitly and flag it as a side effect.
  • Test the packed tarball in a separate project before publishing.

Next: Project: A Static Site Generator