Because my needed to develop a Vue component library that could be published to npm and installed via npm, I searched many articles online and finally completed the task. During this process, I encountered many pitfalls, and I’ve organized them here, hoping to help those who may need it.
I used Vue CLI 3 for development, which is quite simple to install and convenient to use. Official Vue CLI 3 Link;
Environment Preparation
1 | npm install -g @vue/cli / yarn global add @vue/cli |
Creating the Project
First, install the scaffolding globally, then create a new project with vue create hello-world
. Press enter through the prompts to successfully create the project.
After the project is created, start it with npm run serve
and then open http://localhost:8080/
. If you see Welcome to Your Vue.js App, the project has been successfully created.
Modifying Files
Before modification, the project directory looks like this:
After modification, the project directory looks like this:
In the src
directory, create a new index.js
file as the entry point for exporting components. All components will be referenced and exported in src/index.js
, and the final packaging will be compiled based on the configuration inside index.js
.
1 | import xxx from './components/xxx/xxx.vue' |
Then edit the build script in package.json
:
build-bundle: "vue-cli-service build --target lib --name libraryName ./src/index.js";
The --name libraryName
specifies the name of the project to be published, and ./src/index.js
is the path to find the exported components.
1 | "scripts": { |
Then execute npm run build-bundle
You will see a new folder dist
with various versions of JavaScript files ready for publication. We choose the common.js as the file for publication.
npm Publishing
npm login
to log in to npm, enter your username, password, and email.
Remember to update the version number when publishing. Each publication requires an updated version number, which cannot be retracted, so be careful! There are three ways to update the version number:
1 | For example, if I want a 1.0.1 version, note that the last digit has been increased by 1, then the command: `npm version patch` and press enter; |
npm publish
to publish (Note that the package name should not conflict with others, it’s best to check in advance) and then the publication is successful. This way, you can install it with npm i xxx
.
Component Reference
1 | import xxx from 'xxx' |
Summary
1 | The above is how I created a component library from scratch. It may not be perfect, but it is my experience and summary, hoping to help those who need it. I think that if you want to develop a component library, you should be able to succeed based on the above code. |
Finally, note that the name must be included in the component’s Vue file. I made the mistake of not having a name and kept getting errors.