Many developers are familiar with using a component library (e.g. Vuetify, Quasar, PrimeVue, etc.), but there comes a time when it’s useful to create your own.
- Multiple projects which should share custom components.
- A large project which is hard to test.
This comprehensive, step-by-step guide1 will take you from a new, empty folder all the way to a fully-functional component library with robust automated testing tools which follow software engineering best practices. The techniques described here are neither theoretical nor a mere “proof-of-concept” – they have been used successfully in critical production applications.
Let’s get started!
1. Scaffold an empty Vite project
Vite is a fabulous build tool that works especially well with Vue projects like a Vue Component Library.
Run npm create vite@latest to scaffold a new project. You’ll be asked for a project name, then choose the Vue framework and the TypeScript variant to complete the setup.
1$ npm create vite@latest
2
3Need to install the following packages:
4[email protected]
5Ok to proceed? (y) y
6✔ Project name: … my-component-library
7✔ Select a framework: › Vue
8✔ Select a variant: › TypeScript
9
10Scaffolding project in /my-component-library...
11
12Done. Now run:
13
14 cd my-component-library
15 npm install
16 npm run devRun the recommended commands to verify that installs and works correctly.
Open your browser to the Local URL shown in your console to see the your new webpage powered by Vite!
To wrap up scaffolding, let’s do a few tiny polishing steps…
Install TypeScript types for NodeJS APIs
Currently, newly scaffolded Vite projects do not include the TypeScript type declarations for built-in NodeJS APIs. We’ll need these later in the guide.
1npm install --save-dev @types/node
Create an .nvmrc file (optional)
Many developers (and CI tools) use nvm (Node Version Manager) to easily configure the correct NodeJS version for each project. Creating an .nvmrc file clearly communicates your project’s preferred version of node.
1node --version > .nvmrc
Make a git commit (optional)
At this point, I like to make a commit to snapshot my progress
Committing immediately after scaffolding gives two major benefits: first, I can easily revert back to the scaffolded version if I mess up a later step; and second, a git blame can distinguish default configurations from custom configurations.
2. Create some sample library code
Let’s add some placeholder code to our library! The goal at this point is have just enough library code to meaningfully evaluate the build tooling we will add in later steps. As such, I strongly recommend starting with only trivial library code so you can focus any debugging efforts on the build tooling.
For this tutorial, we’ll use a simple Greeting component which calls a utility function to generate its greeting.
Create a custom utility function
And create a custom component
For now, ignore the TypeScript error on the import line. We’ll fix that in a later step.
Finally, export your component from your library
1export * as Greeting from "./components/Greeting.vue"At this point, if you run npm run build you’ll notice that the generated dist directory contains none of the library code you just wrote. We’ll fix the build in the next step.
3. Convert Vite to library mode
A newly scaffolded Vite project always starts in project mode (i.e. building a complete web application), but, with a little more configuration, Vite also supports building JavaScript libraries.
How does Vite's project mode work?
Understanding the “magic” behind Vite’s project mode isn’t required for building a component library. But that knowledge does make it easier to understand the changes made to support library mode in Vite.
When you run npm run dev, here’s what happens behind the scenes:
npmparses yourpackage.json, looks in thescriptssection to find the configureddevcommand.npmruns thedevcommand (in this casevite) in the context of your currently installednode_modules.- Vite loads its config file
vite.config.tsand starts an http server rooted atindex.html, the default entrypoint for the new Vite project. - Notice thevueplugin which enables Vite to transpile.vuefiles to plain JS.
Opening a web browser loads the index.html like a normal webpage, opening your web application.
- The
index.htmldefines an empty<div id="app"></div>(where the web application will mount). - The
<script type="module" src="/src/main.ts"></script>loads thesrc/main.tsscript (dynamically transpiled to JS by Vite) which creates the Vue app and mounts it at the previously defineddiv.
You’ll notice that if you run npm run build, Vite will create a dist directory containing index.html (the default entrypoint) and the optimized code from your src directory. The key difference for library mode is telling Vite to build a different entrypoint to your code.
Create a library entrypoint
In Step 2, we created a separate lib folder for our library code. We left the index.html file and src directory alone since they are a helpful playground to use while building components.
Now we need to add the library entrypoint to vite.config.ts
Setting
build.copyPublicDirtofalseexcludes files in thepublicfolder from the build. For libraries, that’s typically the preferred option sincepublicis intended to hold static assets for a webpage.
The default value for
build.lib.formatsis['es', 'umd']. The'umd'format is mostly used for standalone JS files distributed via a CDN, so it isn’t necessary for a component library. Omitting'umd'also has the benefit of allowing us to omit thebuild.lib.namekey.
Now, running npm run build will generate a bundle in the dist folder containing your library code instead of the src code!
TypeScript Support in the IDE
Right now, TypeScript doesn’t work in our library code because the default configuration only looks at the src code. Let’s fix that!
Copy Vite’s types to your library
1cp src/vite-env.d.ts lib/vite-env.d.tsEnable TypeScript in your IDE for the lib directory
TypeScript should now be working in your IDE!
Add TypeScript declarations to the built library
We also want to include TypeScript type declarations in the built library so that library users also benefit from the IDE autocompletion and quality checks. However, we want to omit type declarations for src files (our dev playground) since the src code won’t be there either.
Start by creating a separate TypeScript config for building the library
And update your package.json’s build script to use the new TypeScript config. Now your build will only run type checks for code in your lib directory.
To distribute TypeScript type declarations with your library, install the Vite plugin called vite-plugin-dts and point it to the tsconfig-build.json you just created.
1npm add --save-dev vite-plugin-dtsNow, npm run build should include several .d.ts files in your dist folder containing the TypeScript declarations for your library code!
4. Optimize the build
At this point, the built library bundle is nearly 50kb, a huge amount of code for such a simple component library. The reason for the excessive size is that our build is packaging in a copy of Vue. Since our component library will be used within projects which already have Vue installed, this additional bundling is entirely unnecessary.
Remove Vue from the bundle
Let’s update our Vite config to exclude Vue from the built library bundle
We’ll also want to mark Vue as a peer dependency so that our library users are reminded that they need to install Vue themselves.
You’ll also want to add Vue as a development dependency so it continues to be installed while you develop the library.
1npm install --save-dev vueNow npm run build produces a much more reasonably sized bundle of only ~0.5kb, a 100x size reduction!
5. Add testing tools to verify software quality
Add Storybook.js for Component Driven Development
As we add more components to our library, it is helpful to have a dedicated tool to preview and test our components. The most powerful of these tools is Storybook.js.
Install Storybook
You can install Storybook using their installation guide for Vue projects, but I’ll repeat the key steps here for completeness.
NOTE: At the time of writing, there is a shortcoming with the current Storybook install script. You may have to force
npmto resolve the packagejackspeak(one of Storybook’s transitive dependencies) to a specific version.
Install Storybook.js
1npx storybook@latest initStorybook should automatically configure itself and launch in your browser at https://localhost:6006. Explore the tool to get a feel for what it does and how it works.
Add a Story for a library component
Stories are written in files named *.stories.ts and, by convention, are placed next to the component they test.
Create a Story file for the Greeting.vue component we created at the beginning of the tutorial.
1import type { Meta, StoryObj } from '@storybook/vue3';
2
3import Greeting from './Greeting.vue';
4
5// CONFIGURATION
6const meta = {
7 title: 'components/Greeting',
8 component: Greeting,
9 tags: ['autodocs'],
10} satisfies Meta<typeof Greeting>;
11
12export default meta;
13type Story = StoryObj<typeof meta>;
14
15// STORIES
16export const Default: Story = {
17 args: {},
18};
19
20export const HelloWorld: Story = {
21 args: {
22 name: 'World',
23 },
24};To show this story within Storybook in your browser, you’ll have to tell Storybook to look for stories in the lib folder. For this tutorial, we won’t be writing stories for anything in the src folder so we’ll have Storybook ignore src entirely.
Restart Storybook for this config change to take effect.
1npm run storybookYour Greeting story should now available in your Storybook!
Add testing addons to Storybook
Storybook supports a rich ecosystem of addons for testing your components.
Install the Accessibility Addon
I like starting with the Accessibility addon since it provides a solid foundation for later testing plugins (particularly interaction testing).
1npm install --save-dev @storybook/addon-a11yNow your stories will have an Accessibility tab which automatically checks your component for Accessibility issues and recommends fixes.
Install the Storybook Test Runner
The Storybook Test Runner turns all of your stories into automated unit, smoke, and interaction tests, no extra effort required!
Install the test runner
1npm install --save-dev @storybook/test-runner @storybook/testing-libraryInstall playwright (used by the test runner for smoke and interaction tests)
1npx playwright installStart Storybook in one terminal
1npm run storybookAnd run the tests against that Storybook instance in another terminal
1npm run test-storybookAdd Storybook Test Coverage
Measuring your test coverage – which lines of production code get executed while running the test suite – can help you find gaps in your testing.
To have Storybook collect test coverage during its test runs, install the Storybook Test Coverage Addon
1npm install --save-dev @storybook/addon-coverageYou’ll also need to include the coverage addon in your Storybook configuration
To measure test coverage in your .vue files, you’ll also need to a .nycrc.json config file instructing the test runner to instrument .vue files.
1touch .nycrc.json1{ "extension": [".vue",".js","jsx",".ts","tsx"] }Restart your Storybook instance if necessary, then rerun the test suite, this time with the --coverage flag.
1npm run test-storybook -- --coverageThe coverage metrics will be saved to coverage/storybook/coverage-storybook.json. You can generate a coverage report using nyc.
1$ npx nyc report --reporter=text --temp-dir coverage/storybook
2--------------------|---------|----------|---------|---------|-------------------
3File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
4--------------------|---------|----------|---------|---------|-------------------
5All files | 100 | 100 | 100 | 100 |
6 components | 100 | 100 | 100 | 100 |
7 Greeting.vue | 100 | 100 | 100 | 100 |
8 utils | 100 | 100 | 100 | 100 |
9 createGreeting.ts | 100 | 100 | 100 | 100 |
10--------------------|---------|----------|---------|---------|-------------------
11
12$ npx nyc report --reporter=text-summary --temp-dir coverage/storybook
13=============================== Coverage summary ===============================
14Statements : 100% ( 4/4 )
15Branches : 100% ( 2/2 )
16Functions : 100% ( 1/1 )
17Lines : 100% ( 4/4 )
18================================================================================Add Vitest for unit testing for utility functions
Your library may include utility functions in addition to UI components. To test these utility functions directly, you can add a unit testing framework like Vitest.
Install vitest
1npm install --save-dev vitest Add a test script to your package.json
Add a test file for the createGreeting.ts utility function we created at the start of the tutorial
1import { describe, expect, it } from "vitest"
2import { createGreeting } from "../createGreeting"
3
4describe("createGreeting", () => {
5 it("creates a generic greeting when no name is provided", () => {
6 expect(createGreeting()).toBe("Hello!")
7 })
8 it("creates a specific greeting when a name is provided", () => {
9 expect(createGreeting("World")).toBe("Hello World!")
10 })
11})Now you can run the unit tests for your utility code
1npm run test:unitSetup Test Coverage Measurement for Vitest
Create a vitest.config.ts with the following contents
1import { defineConfig } from 'vitest/config'
2import vue from "@vitejs/plugin-vue"
3import tsconfigPaths from "vite-tsconfig-paths"
4
5export default defineConfig({
6 test: {
7 coverage: {
8 all: true, // Include files with 0% coverage in the report.
9 provider: 'istanbul', // or 'v8'
10 include: ['lib/**/*'],
11 // Omit test code from the report (both Storybook and Vitest)
12 exclude: ['lib/**/*.stories.{ts,tsx}', 'lib/**/*.test.{ts,tsx}'],
13 reporter: ["text", "text-summary", "json", "json-summary"],
14 reportsDirectory: "coverage/unit",
15 },
16 },
17 plugins: [
18 vue(),
19 tsconfigPaths(),
20 ],
21})Install vite-tsconfig-paths so Vitest can better support TypeScript resolutions.
1npm install --save-dev vite-tsconfig-pathsRun the unit tests with the --coverage flag to see the coverage results. If you are prompted to install @vitest/coverage-istanbul, accept it, then re-run the test command.
1npm run test:unit -- --coverageCombine Test Coverage Results from Storybook and Vitest
Since we’re running two different testing tools, we get two separate, and thus incomplete, test coverage reports. We want to merge those reports into one complete test coverage report.
Currently, the data backing the Storybook test coverage report is saved in the coverage/storybook/ folder while Vitest’s test coverage data is in coverage/unit/
The underlying CLI tool for test coverage, nyc, has a built-in merge command which will merge all test coverage reports found in a specified directory. As a result, we can use the following script to generate our combined report
Now you can view a complete, combined test coverage report:
1$ npx nyc report --reporter=text --temp-dir coverage/
2--------------------|---------|----------|---------|---------|-------------------
3File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
4--------------------|---------|----------|---------|---------|-------------------
5All files | 100 | 100 | 100 | 100 |
6 components | 100 | 100 | 100 | 100 |
7 Greeting.vue | 100 | 100 | 100 | 100 |
8 utils | 100 | 100 | 100 | 100 |
9 createGreeting.ts | 100 | 100 | 100 | 100 |
10--------------------|---------|----------|---------|---------|-------------------
11
12$ npx nyc report --reporter=text-summary --temp-dir coverage/
13
14=============================== Coverage summary ===============================
15Statements : 100% ( 4/4 )
16Branches : 100% ( 2/2 )
17Functions : 100% ( 1/1 )
18Lines : 100% ( 4/4 )
19================================================================================Running Tests in a Continuous Integration System
Running your tests regularly in an automated environment helps you find and fix errors in your code faster.
To run our tests in a continuous integration system (e.g. GitHub Actions), we need to write scripts that:
- Run the tests headlessly (i.e. with zero user interaction).
- Specify all dependencies required for the production code and its tests.
Run headless tests locally
Let’s start by updating the scripts in package.json to clearly specify whether they run interactively (for local development) or headlessly (for use in ci).
1 "scripts": {
2+ "cdd": "storybook dev --port 6006",
3+ "test:unit": "vitest",
4+ "test:unit:ci": "vitest --coverage --run",
5+ "test:cdd": "test-storybook --watch --browsers chromium,firefox,webkit",
6+ "test:cdd:ci": "test-storybook --coverage --browsers chromium,firefox,webkit",
7+ "build": "vue-tsc -p ./tsconfig-build.json && vite build --watch",
8+ "build:ci": "vue-tsc -p ./tsconfig-build.json && vite build",
9+ "build:cdd": "storybook build",
10 }
I use the name
cdd(shorthand for Component Driven Development) to refer to my Storybook scripts because I prefer to focus on engineering principles over the tool that enables them.
From there, we can write the scripts to use in CI. I like to use a Makefile for this purpose
1.PHONY: build
2build:
3 npm run build
4
5.PHONY: build-ci
6build-ci:
7 npm run build:ci
8
9
10.PHONY: test
11test:
12 npx --yes concurrently --kill-others --success first --names "CDD,UNIT" -c "magenta,blue" \
13 "npx --yes npm run test:cdd" \
14 "npx --yes npm run test:unit"
15
16.PHONY: test-ci
17test-ci:
18 rm -rf coverage
19# Run the unit tests
20 npm run test:unit:ci
21# Run the Storybook tests
22# - Credits: https://storybook.js.org/docs/writing-tests/test-runner#run-against-non-deployed-storybooks
23 npx --yes concurrently --kill-others --success first --names "SB,CDD" -c "magenta,blue" \
24 "npx --yes npm run cdd -- --port 6006 --ci --quiet" \
25 "npx --yes wait-on tcp:6006 && npm run test:cdd:ci"
26# Merge the coverage reports
27 mkdir --parents coverage/merged
28 cp coverage/storybook/coverage-storybook.json coverage/merged/coverage-storybook.json
29 cp coverage/unit/coverage-final.json coverage/merged/coverage-unit.json
30 npx nyc merge coverage/merged coverage/coverage-final.json
31# Generate the coverage report
32 for reporter in text text-summary lcov json-summary ; do \
33 npx nyc report --reporter=$$reporter -t coverage/ --report-dir coverage/ ; \
34 doneWith this Makefile you now have four useful commands for local development and CI verification
The magic part of these scripts is the use of the concurrently package to boot a Storybook server headlessly for the Storybook testing library to run against.2
Run tests in GitHub Actions
If you host your component library repository in GitHub, you can create a GitHub Actions workflow file which will run the tests for you on every commit you push up.
1name: "CI(branch): Test, Release"
2
3on:
4 push:
5 branches: [master, qa, dev, "[0-9]+.[0-9]+.[0-9]+", "[0-9]+.[0-9]+.[0-9]+-[a-zA-Z]+"]
6 tags:
7 - "[0-9]+.[0-9]+.[0-9]+"
8 pull_request:
9 branches: [master, qa, dev, "[0-9]+.[0-9]+.[0-9]+"]
10 workflow_dispatch:
11
12jobs:
13 test:
14 runs-on: ubuntu-latest
15 steps:
16 - uses: actions/checkout@v4
17
18 - uses: actions/setup-node@v4
19 with:
20 node-version-file: '.nvmrc'
21
22 - name: Install dependencies
23 run: yarn install --frozen-lockfile
24
25 - name: Install Playwright
26 run: npx playwright install --with-deps
27
28 - name: Build the package
29 run: make build-ci
30
31 - name: Run the Unit Tests
32 run: make test-ci
33
34 - name: Publish internal package releases
35 # Run only on `push` events to tags/branches other than `master`
36 if: github.ref_name != 'master' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch')
37 run: |
38 echo "NO-OP: Replace with your code for publishing an internal version"
39
40 - name: Push the production package releases
41 # Only run this job for the `master` branch
42 if: github.ref_name == 'master'
43 run: |
44 echo "NO-OP: Replace with your code for publishing a production version"6. Other Notes
Hot-reloading the Vue component library within a larger project
My original motivation for creating a component library was to improve the testability of a large Vue application, not to share components between multiple applications. In that situation, my team wanted to preserve the ability to edit the component library and see it hot-reload within the large Vue application.
Attempting to hot-reload code changes to an npm dependency is extraordinarily difficult.
- The dependency code is usually an optimized, compiled form of the original source code, so a hot-reload requires rebuilding the original source code. Vite’s
build --watchmode impressively managed to effectively tree-shake the build process so that it only rebuilt the smallest number of JS chunks possible; however, even that optimized build still took 3-4 seconds for tiny code changes (e.g. changing a static text label). - npm dependencies are loaded from
node_modules, which is only updated bynpm install. Any hot-reload process would also need to automatically re-install the component library.
For these reasons, we decided to import our component library code directly (i.e. not as an npm dependency) and let our larger Vue project’s compiler handle the entire build process for both the library code and the main application code.
Include your component library within the larger project as a submodule
Within the larger project, configure resolution aliases for your component library’s code.
Add a TypeScript alias
Add a Vite alias
Now your larger Vue project can directly import code from your component library and have the library code hot-reload/build just like the code of the larger application.
1import Greeting from "my-component-lib/components/Greeting.vue"Conclusion
Testing UI code is can be really hard, especially when attempting to improve the testability of a large, established project. Creating a custom component library can (1) provide a clean environment for developing and testing individual components and (2) open the door to sharing code with between projects for further productivity gains.
I hope this tutorial has helped you create a robustly testable component library which can provide a solid foundation for your development work for years to come.
Please share your experience, insights, and/or critiques in the comments below!