Introduction#
Recently, I read the documentation for Vite and found that it has a library mode which is quite convenient for packaging, so I decided to write a blog post to document the process.
Basic Configuration#
Run the following command to create a React + TypeScript project
Delete the src and public folders, and create example and packages folders, where example stores component examples or debugging components, and packages stores component source code. Also, don't forget to modify the script path in the root directory index.html.
Note: For related eslint, prettier, and tsconfig configurations, please refer to the end of the git repository, as this is not the focus of this article.
Next, let's open vite.config.ts and configure the packaging (remember to install @types/node first).
At this point, you can export some code in the packages/index.tsx folder, and it should be correctly packaged into CommonJS and ESM.
Component Development#
To keep it simple, we will create a Tag component that has type support and can change colors.
Install dependencies
The following React code will not be introduced.
Create packages/Tag/interface.ts
Create packages/Tag/index.tsx
Create packages/Tag/style/index.less
Create packages/Tag/style/index.ts
Create packages/index.tsx
Note: At this point, if we try to package, it will throw an error because we have not installed the @rollup/plugin-typescript plugin, which is needed to package TypeScript types and generate d.ts files.
Go to vite.config.ts and import the plugin
Now, when we execute pnpm build, the packaging is complete, generating the following directory

Publish to npm#
However, at this point, if we publish the package to npm, users still won't be able to use it. We also need to define some basic entry information and type declarations in package.json:
After completing this, execute the following command to publish to npm.
Then, in your other projects, you can import it, and it will display normally with TypeScript type hints.
Thus, the main part of a simple component library has been developed (though it is quite imperfect), and now we will introduce unit testing.
Adding Unit Tests#
We will use Vitest for unit testing:
Open the vite.config.ts file and add type declarations at the first line of the file, and add a few lines of configuration in defineConfig to let rollup handle .test files:
Next, open package.json and add npm commands:
Generally, we will place the test code in the __test__ folder, so create packages/Tag/__test__/index.test.tsx with the following code:
Run pnpm test to perform unit testing successfully.

Complete Code#
Complete code repository: https://github.com/suemor233/suemor-design-demo