Skip to content

Create a React Library

This guide will bootstrap a publishable React library with Vite, with the following features:

Setup base project

  1. Follow this guide to create a React SPA

Configure Library Mode

  1. Create src/index.ts with the exports for your library

    src/index.ts
    import App from "./App";
    
    export { App };
    
  2. Update the vite.config.js with the following

    vite.config.js
    import { resolve } from "path";
    import { defineConfig } from "vite";
    import packageJson from "./package.json";
    
    export default defineConfig({
        build: {
            lib: {
                // Could also be a dictionary or array of multiple entry points
                entry: resolve(__dirname, "src/index.ts"),
                name: "MyLib",
                // Name the same as the source file
                fileName: "index",
                // Output ESM modules only
                formats: ["es"],
            },
            rollupOptions: {
                external: [
                    ...Object.keys(packageJson.peerDependencies),
                    // Include jsx runtime too
                    "react/jsx-runtime",
                    // (only needed if using MUI) Mark all mui imports as external
                    /@mui\/.*/,
                ],
            },
        },
    });
    
  3. Fix TypeScript errors in the config by editing tsconfig.node.json

    tsconfig.node.json
    {
        "compilerOptions": {
            "resolveJsonModule": true
        },
        "include": ["vite.config.ts", "package.json"]
    }
    
  4. Add @types/node package to resolve "path" package

    pnpm i -D @types/node
    
  5. Update the package.json to include the exports and setup dependencies

    package.json
    {
        "type": "module",
        "files": ["dist"],
        "module": "./dist/index.js",
        "types": "./dist/index.d.ts",
        "exports": {
            ".": {
                "import": "./dist/index.js",
            }
        },
        "scripts": {
            // Ensure that `tsc` is ran after `vite build`,
            // otherwise `vite build` will clear what `tsc` generates
            "build": "vite build && tsc"
        },
        // Rename "dependencies" to "peerDependencies"
        "peerDependencies": {
            "react": "^18.2.0",
            "react-dom": "^18.2.0"
        },
        // Add all "peerDependencies" to "devDependencies"
        "devDependencies": {
            "react": "^18.2.0",
            "react-dom": "^18.2.0"
        }
    }
    
  6. Configure TypeScript to export types by editing tsconfig.json

    tsconfig.json
    {
        "compilerOptions": {
            // Remove "noEmit" line
            "emitDeclarationOnly": true
            "outDir": "dist",
            "declaration": true,
        }
    }
    

Next Steps


Last update: August 12, 2023
Created: May 27, 2023