As we all know, vue components are meant to be reused. This process is rather easy when working with a single application but how about using the same vue components across multiple vue applications? copy and paste? This can work but it becomes very inefficient in terms of maintenance. Best practice? The best practice so far is to package the vue component and publish it to npm in order to have to a central entry point to the component which makes changes available to all applications making use of the component. In this article, I'll put together some guidelines and resources to get this up and running.
Creating the component
To begin with you'll need to create your vue application which will host your reusable component. While building out your component, you'll want to do this in partial isolation of the vue environment. This means you'll not be able to preview what you're building and also know if it works fine. To make up for this, you can make use of Storybook. Storybook is an open source platform that is used to build UI components in isolation. It has amazing features and I 100% recommend it. It also has a pretty decent community to help you get started.
Packaging the component
In order to publish your component to npm, you'll to need to first package the component into distributable builds. Here's reference articles that explain how to do this properly.
For vue 2:
https://vuejs.org/v2/cookbook/packaging-sfc-for-npm.html
For vue 3:
https://v3.vuejs.org/guide/single-file-component.html#building-with-rollup
Testing out the packaged component
Before publishing to npm, you'll want to test out your component in a sample vue application to be sure everything plugs in nicely. To do this, you can use the script below to build and package your component into an installable .tgz file, move the .tgz file to the sample vue application and also install the the packaged component via npm
#!/usr/bin/env sh
# abort on errors
set -e
# build
npm run build
npm pack
cp vue-packaged-component-0.1.0.tgz ~/sample-vue-application-path
cd ~/sample-vue-application-path/
npm i vue-packaged-component-0.1.0.tgz
After running the script, your component will be available in the sample vue application and you can test it out there.
Publishing to npm
This is pretty much an easy step. Put together a workflow that works for you and the rest is just a repetitive procedure. Well, you don't have to think too much about putting this together, this article How to publish packages to npm (the way the industry does things) will show you how to get through this step.
You're done! your component will be published to npm and ready to be used in multiple applications. To view a project I've created and published using this workflow you can check out https://github.com/a4anthony/vue-inline-svgs and https://www.npmjs.com/package/vue-inline-svgs.
Thank you for your time and I hope this turns out really helpful.