How to Reuse Vue Components Between Projects

Vue.js is a great framework that gives you the power to compose your UI out of components. A great advantage of this modularity is the ability to reuse components across different projects, applications, and even teams.

But, separating components into different repos just to publish them is a lot of overhead, and the workflow for reusing them is limiting. But, using modern tooling for components things can be simpler and a lot more limitless.

In this post, we’ll learn how to leverage modern tools like bit to easily share Vue components between projects, without having to split repos, refactor or configure anything. In a few minutes, you can share a component in two apps, while changes can be made from both sides and synced between them.

This is image title

Through Bit, each component is seamlessly isolated from the project, published and reused in any other project in a very short time. As a useful side-product, you will gain a reusable “lego-box” of components your team can share across projects, and gradually build a component design system.

What you will learn…

This is image title

  • Track and isolate a component- no refactoring.
  • Build the component in isolation- no configurations.
  • Publish the component from the project; and nothing else.
  • Install the component in another project with npm/yarn.
  • Modify the code right from the new project using Bit and update the changes as a new version- no context switching.
  • Sync and merge code changes between the projects.

No point in writing the same code twice, right? Let’s get to it. For any questions, don’t hesitate to reach out to the community channel on Gitter.

Short one-time setup

First, you need to verify that you have Node 10.9+ installed.

To run this tutorial, clone and setup the Vue tutorial project:

git clone https://github.com/teambit/bit-vue-tutorial
cd bit-vue-tutorial
npm install

Setup Bit

Head over to bit.dev and create your free account. When you are logged into bit.dev you can create a collection. A collection is a remotely-hosted set of components that are ready to be shared and used across your applications.

Install and authenticate Bit CLI

Install Bit CLI on your computer using npm:

npm install bit-bin -g

Visit Install Bit for other installation methods.

Great. Now, authenticate Bit to your bit.dev account by running the following command. This will let you share and consume components from your workspace to your bit.dev account.

bit login

In addition, Bit adds the npm registry used by Bit to your npmrc configuration, so you can install components using your npm client.

Initialize a Bit Workspace for your project

Switch to the Vue tutorial project your cloned run the Bit initialization command. This will create a bit workspace for the project so that Bit can help you manage, build and publish the components in isolation from the project.

$ bit init
successfully initialized a bit workspace.

Notice two other changes have happened:

  • A new file named .bitmap has been created in your root directory. This file tracks Bit components and only includes a comment and a line with your bit version.
  • A new section, bit, has been added to your package.json file with the following defaults for your project:
"bit": {
  "env": {},
  "componentsDefaultDirectory": "components/{name}",
  "packageManager": "npm"
}

In your actual project, these changes should be committed to your version control tool system.

Let’s share Vue the component

This is image title

Using Bit you can easily share multiple components from any repository instead of publishing the whole project. Let’s track the product-list component from the Vue tutorial project, and give it the product-list id.

When Bit tracks components, it automatically defines their dependencies and wraps them in an isolated capsule so that they can be used anywhere. Let’s track the product-list component in the demo Vue project you just clones.

Let Bit track and isolate the component

To track the product list component, we will need to tell Bit about the component and the files that are related to it. In Vue, a component is typically a single file so we can directly add this file. We also tell Bit to track the file under the id product-list

$ bit add src/components/productList.vue --id product-list
tracking component product-list:
tracking component product-list:
added src/components/productList.vue

When creating new components, you need to make sure that Bit properly tracks all of the files required for the component. Bit can analyze the component for you and verify that all files are included. You can do that by checking the status of the component:

Our component is using src/assets/products.js - Bit will identify it and alert us about it.

$ bit status
> product-list ...  issues found  
       untracked file dependencies (use "bit add <file>" to track untracked files as components): 
          src/components/ProductList.vue -> src/assets/products.js

You will need to add the missing file to the component. In our case, this file is only used by this component so we will add it to the component. If this file was shared between components, we should track it as a new component.

$bit add src/assets/products.js --id product-list
tracking component product-list:
added src/assets/products.js
added src/components/productList.vue

Check the status again 😏

$ bit status
new components
(use "bit tag --all [version]" to lock a version with all your changes)
     > product-list ... ok

Define a compiler and build the code; no configurations!

So far, we have provided Bit with the source file of the component. But in order to consume the files in other projects, the component needs to be built.

Bit saves you the overhead of configuring the build step of every component. Instead, you can define a compiler for your project’s workspace, so that each component can be built in isolation and run outside of the project.

Bit is storing the source code of the component, but the code should still remain in your version control system (VCS) such as your Git repository.

Bit has a large collection of compilers that are open source and maintained by the Bit team. To build the vue component, you’ll need the Vue compiler. Install the compiler and run this command inside the Vue tutorial repository:

$bit import bit.envs/bundlers/vue --compiler
the following component environments were installed
- bit.envs/bundlers/vue@2.6.10

The version may vary slightly when you run the tutorial

The Vue compiler is now set as the default compiler for the Bit workspace inside this repository. You can check the package.json and verify that the compiler is installed by locating the following entry in the Bit section:

"env": {
      "compiler": "bit.envs/bundlers/vue@2.6.10"
    },

Let’s build the component and see that it’s ready to run anywhere. The build is taking place in an isolated environment to make sure the process will also succeed on the cloud or in any other project. To build your component, run this command inside your Vue project:

bit build

This results in the component name (product-list) followed by a list of file names. Those are the built files of the component.

Export (publish) the component from the project

With the component properly built, it is now time to share it with the world.
Components are versioned according to semver standards. To tag your component with a version, run the following command:

$ bit tag --all 0.0.1
1 component(s) tagged
(use "bit export [collection]" to push these components to a remote")
(use "bit untag" to unstage versions)
new components
(first version for components)
     > product-list@0.0.1

This command tags all the components that are currently staged in Bit. In our case, it’s only the product-list component.

You can check the component status (bit status) and you’ll find the following:

$ bit status
staged components
(use "bit export <remote_scope> to push these components to a remote scope")
     > product-list. versions: 0.0.1 ... ok

The important thing to notice here is that the component is considered staged. That means that it is now ready to be exported.

To export the component to your bit.dev collection, we will use the export command and the full name of the collection, structured as <username>.<collection>:

$ bit export <username>.vue-tutorial
exported 1 components to scope <username>.vue-tutorial

The component is now visible in your collection on bit.dev. You can access it in https://bit.dev/<username>/vue-tutorial. You can also visit the component created for this demo at: https://bit.dev/bit/vue-tutorial

At this point, checking bit’s status will no longer display the component as the component is now hosted on the remote collection:

$ bit status
nothing to tag or export

If you want to see all the components you have you can run:

$ bit list

You will get a list of all components and their versions.

Right now, the component code is in your local project (and should be committed to your source control), but it is also available for other projects.

Discover and explore your reusable components

This is image title

The Vue component is now available in the bit.dev platform, which helps developers and team share components and collaborates to speed and standardize development through shared components.

In the platform, every component you share becomes available to discover, visualize, sandbox and use right off the shelf in any new project.

You can access the component you just shared at the following url or explore this demo component:

https://bit.dev/<username>/vue-tutorial/product-list

In few seconds you will see the component rendered in the playground. You can view an example here. On the component’s page, you can also see the different commands available for installing this component using yarn or npm. You can copy the yarn command; we are going to use it very soon.

Install the component in a new project

This is image title
This is image title

Ok, so now the Vue component is ready for reuse! Let’s install in it another project. You can choose your own, or use the Vue CLI (version 3) to generate a new application and then switch to a new directory:

npx @vue/cli create my-new-vue

If you already have vue-cli installed globally you can run:

vue create my-new-vue

Make sure you are using babel and es6.

In your terminal, switch to the my-new-app directory.

Install the component with npm

Use your favorite package installer (npm or yarn) to install the component.
The component is stored in the Bit registry, so the full path to the component will be: @bit/<username>.<collection name>.<component name>

If you didn’t run bit login earlier, you can configure bit.dev as a scoped registry to your npm and yarn clients using this command. if you did, no need to do it again.

npm login --registry=https://node.bit.dev --scope=@bit

Then just run the install command using npm:

npm install @bit/<username>.vue-tutorial.product-list --save

The component is now added to your package.json:

"@bit/<username>.vue-tutorial.product-list": "0.0.1"

Use in your application

Now you can use the component in your code, just like any other import. Your app component should look like this:

<template>
  <div id="app">
    <ProductList />
  </div>
</template>
<script>
import ProductList from '@bit/<username>.vue-tutorial.product-list';
export default {
  name: 'app',
  components: {
    ProductList
  }
}
</script>

Last but not least, run your application using Vue CLI:

npm run serve

Voila! You can now see the component list inside the newly created application.

Use Bit to modify the code right from the new project (!)

This is image title

A cool thing about Bit is that it lets you import and develop the code of any component right from any consuming projects, and update the changes as a new version of the component which can be also updated anywhere else.

Next, we are going to make a change to the component and export it back to the collection. We will add a View button to the product list. For simplicity, it will only show an alert saying the product has been viewed.

Import the Component

Up until now, the product-list component was only installed (in its built form) in our project. Now, we want to import the code into our project to make the changes.

In order to import the component, initiate the my-new-app workspace as a Bit workspace:

bit init

After the confirmation message that the workspace was initialized, run the following command:

$ bit import <username>.vue-tutorial/product-list
bit import <username>.vue-tutorial/product-list
successfully imported one component
- added <username>.vue-tutorial/product-list new versions: 0.0.1, currently used version 0.0.1

Notifications on missing core dependencies are ok. You should already have those packages in your project.

The command is also available on the component page.
Here is what happened:

  • A new top-level components folder is created that includes the code of the component, with its compiled code and node_modules (in this case the node_modules are empty, as all of your node_modules are peer dependencies and are taken from the root project.
  • The .bitmap file was modified to include the reference to the component
  • The package.json file is modified to point to the files rather than the remote package. Your package.json now displays:
"@bit/<username>.vue-tutorial.product-list": "file:./components/product-list"

Start your application to make sure it still works. As you’ll see, no changes are required: Bit takes care of everything.

Update the code

Let’s modify the product-list component. Change the components/product-list/ProductList.vue to include the following method:

view() {
    window.alert('The product has been viewed!');
 }

Change the template to include the new button:

<template>
    <div>
        <h2>Products</h2>
        <template v-for="(product, index ) of products">
            <div v-bind:key={index}>
                <h3>
                    <a>
                        {{ product.name }}
                    </a>
                </h3>
                <p v-if="product.description">
                    Description: {{ product.description }}
                </p>
                <button @click="share">
                    Share
                </button>
                <button @click="view">
                    View
                </button>
            </div>
        </template>
    </div>
</template>

Run the Vue application:

npm run serve

The app is not yet changed. That’s because the Bit components are compiled by the bit compiler. In a separate terminal, run the bit build command to compile the changes. You should see that the compiler is installed:

successfully installed the bit.envs/bundlers/Vue@2.5.2 compiler

That will be followed by a successful compilation of the main file.

In order to compile the application, we need to enhance the bit webpack configuration to properly work with symlinks.
Add a new file vue.config.js with the following configuration:

module.exports = {
    configureWebpack: {
        resolve: {
            symlinks: false // support npm link
        },
    }
}

Run the my-new-app again and you’ll now see the changed component with the view button.

In a real project, it is recommended to commit those changes to your GitHub repository.

Update the code changes

Next, export the changes done to the component back to bit.dev.

bit status

The product-list component was modified:

modified components
(use "bit tag --all [version]" to lock a version with all your changes)
(use "bit diff" to compare changes)
     > product-list ... ok

Tag and export the component as a new version. By default this is a semver patch version:

$ bit tag product-list
1 component(s) tagged
(use "bit export [collection]" to push these components to a remote")
(use "bit untag" to unstage versions)
changed components
(components that got a version bump)
     > <username>.vue-tutorial/product-list@0.0.2

Export it back to the collection:

$ bit export <username>.vue-tutorial
exported 1 components to scope <username>.vue-tutorial

Head to the component page on bit.dev. Here you can see that the component has a new version. The changes are also visible on the component playground.

Get component updates

In this last stage, you’ll import the changes to the original project. Switch back to vue-tutorial.

Import code changes

Run bit import to see if any components were changed (similar to doing git pull to check git changes). We will see that the product-list component was changed and a new version exists:

$ bit import
successfully imported one component
- updated <username>.vue-tutorial/product-list new versions: 0.0.2

The component is downloaded but is not yet changed. Check the workspace status, you will get the following:

$ bit status
pending updates
(use "bit checkout [version] [component_id]" to merge changes)
(use "bit diff [component_id] [new_version]" to compare changes)
(use "bit log [component_id]" to list all available versions)
    > <username>.vue-tutorial/product-list current: 0.0.1 latest: 0.0.2

Checkout

Merge the changes done to the component to your project. The structure of the command is bit checkout <version> <component>. So you run:

$ bit checkout 0.0.2 product-list
successfully switched <username>.vue-tutorial/product-list to version 0.0.2
updated src/assets/products.js
updated src/components/productList.vue

Bit performs a git merge. The code from the updated component is now merged into your code.

Run the application again to see it is working properly with the updated component:

npm run serve

That’s it. A change was moved between the two projects. Your application is running with an updated component…

And that’s it! :) Here’s a demo in React, but the idea is just the same:

Conclusion

Reusing Vue components between different projects and applications is a great way to speed development, prevent mistakes and duplications, and create a better consistent expirience for your users.

Trough modern tooling like Bit you can turn component into Lego pieces you can easily build, distribute and reuse anywhere. No overhead and no repo splitting. Feel free to jump in and try it on your own projects, visit Bit on GitHub, read the docs, visit the Gitter channel or say hi :)

Thanks for reading! 🌟

#vuejs #vue #javascript

How to Reuse Vue Components Between Projects
1 Likes91.45 GEEK