How to Create a Component Library with Vite
1. Set up a new Vite project
Start a new project:
npm create vite@latest
Choose React & TypeScript + SWC
Here are 4 things I recommend you to do right after installing Vite:
-
Early first commit Committing regularly is a very good habit. And there is one point in time where it is especially helpful, right after you created a new project and BEFORE you type the first character in your project.
-
Install node's types If working with TypeScript I also install the types package for node. Sooner or later you will need this.
pnpm add -D @types/node
2. Create a lib/main.ts file
Create a folder next to src and name it lib. Inside, create the file which will act as the main entry point of your library, and name it main.ts. When installing the library you can import everything that is exported from this file.
📂 my-component-library
┣ 📂 lib
┃ ┗ 📜 main.ts
┣ 📂 public
┣ 📂 src
…
3. Activate Vite's Library Mode
By default, when running vite build, Vite will transpile the code inside src to the dist folder. What we want instead, is to transpile and ship the code inside of lib.
To activate vite's library mode, inside of our vite.config.ts file, we will need to use the build.lib option.
Like so (do not copy code yet!):
import { resolve } from 'path'
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'
export default defineConfig({
plugins: [react()],
build: {
lib: {
entry: resolve(__dirname, 'lib/main.ts'),
formats: ['es']
}
}
})
