Create a React Library
This guide will bootstrap a publishable React library with Vite, with the following features:
- Built using Vite
- Typechecking with TypeScript
- Code formatting with Prettier
Setup base project
Configure Library Mode
-
Create
src/index.ts
with the exports for your library -
Update the
vite.config.js
with the followingvite.config.jsimport { 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\/.*/, ], }, }, });
-
Fix TypeScript errors in the config by editing
tsconfig.node.json
-
Add
@types/node
package to resolve "path" package -
Update the
package.json
to include the exports and setup dependenciespackage.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" } }
-
Configure TypeScript to export types by editing
tsconfig.json
Next Steps
Last update:
August 12, 2023
Created: June 3, 2023
Created: June 3, 2023