Publishing a Custom Vue Component to the npm Registry
Registering an npm Account
Visit the npm website to create an account. After registration, log in to verify successful access.
Setting Up a Vue Project
Initialize a new Vue project using the Vue CLI. Execute the following command to create a project:
vue create project-name
Run the development server to test the setup:
npm run serve
Packaging the Component
Create a directory named package within the src folder to store components intended for npm publication. Develop your component and test it in App.vue to ensure functionality. Ensure each component has a name property defined.
Inside the package directory, create an index.js file. Organize assets like images in an assets folder and components in a components folder.
Example index.js content:
import ExternalLibrary from 'external-library';
import CustomComponent from './components/customComponent/index.vue';
const componentList = [CustomComponent]; // Add multiple components here if needed
const setup = function(Vue) {
Vue.use(ExternalLibrary);
componentList.forEach(comp => {
Vue.component(comp.name, comp);
});
};
export default setup; // This allows use via Vue.use()
Configuring Project Files
In the root package.json, update the following fields:
{
"private": false,
"main": "src/package/index.js"
}
Adding a Build Script
Add a custom script to the scripts section in package.json for building the library:
{
"scripts": {
"build-lib": "vue-cli-service build --target lib ./src/package/index.js --name component-bundle --dist component-output"
}
}
Execute the build command from the project root:
npm run build-lib
If errors occur, verify the path in the build command matches your directory structure.
Publishing to npm
Navigate to the output directory generated by the build (e.g., component-output). Initialize a new package.json file there:
npm init -y
Review and update the package.json as needed. Ensure the npm registry is set correctly. Use nrm for registry management:
npm install -g nrm
nrm ls
nrm use npm
Log in to npm:
npm login
Check the current registry:
npm config get registry
Publish the package:
npm publish
If you encounter a 402 error, add this to package.json:
{
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.org/"
}
}
Global Registration in a Vue Application
After successful publication, install the package in your Vue project:
npm install your-package-name
In main.js, import and use the component globally:
import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
import YourComponent from 'your-package-name';
Vue.use(YourComponent);
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app');
Use the component in any Vue file by referencing its name property.