Vue is one of the most popular JavaScript frameworks out there and for good reason. Vue makes developing applications easy and fast, and the documentation is very easy to follow.

Vue has a component based architecture that makes it easy to create isolated, reusable components. This is especially useful in large projects where, if no care is taken, things can get pretty confusing.

This article will focus on how you can create external modules for your application.

So let’s get started.

Requirements

To follow along in this tutorial you’ll need:

When you have the requirements listed above, let’s continue.

Why would you need external modules

So why should you create external modules? You can definitely create a module and use it for the project without having to make it external. However, if you are working on it can get bloated easily. With external modules, we can build our modules once and separate them from the codebase, thus keeping it light.

Smaller projects too can benefit from decoupling modules and making them external, though you have to be careful not to over complicate things by creating an external module when you do not need one.

External modules have the following benefits

They are reusable across projects
When we create an external module, we can use the same module across multiple projects. This will make it easier to maintain the code because if you change it once, all you need to do to get the changes across projects is updating your NPM packages.

Make your project, well, modular
Developing modular parts for our application can reduce it’s complexity and make it easier to maintain the separate modules. In larger teams, small groups can be responsible for maintaining certain modules without having to really interact with other parts of the application.

Building an external module

To build our external Vue module, we need to make sure it is one that can be reused across multiple projects and not just specific to a single project.

External modules are commonly referred to as plugins and there is no strictly defined scope for a plugin. There are several types of plugins you can write, and they can perform any the following:

  • Add some global methods or properties. An example of this is vue-custom-element.
  • Add one or more global assets: directives/filters/transitions etc. An example of this is vue-touch.
  • Add some component options by global mixin. An example of this is vue-router.
  • Add some Vue instance methods by attaching them to Vue.prototype.
  • Provide an API of its own, while at the same time injecting some combination of the above. An example of this is vue-router.

When making our external module, we will:

  • Build the component – Every module has a component or a set of components at it’s core.
  • Configure the build system – The build system will compile the module.
  • Deploy the module – Because this has been covered many times, we will link to resources that show how to publish your module to the NPM registry.

Creating a sample module

In order to understand the process we are going to build a sample module. We are going to replicate a user preview feature similar to the one on Twitter where you see the profile when you hover over the profile link:

screenshot of functionality we will replicate

The goal is to to illustrate how to build VueJS modules, not to make a polished finished module. The source to the Module will be linked at the bottom of the article if you want to explore it.

To get started, we need to create a directory to store our module. In that directory, create a package.json file. This file will contain the dependencies we need to build our module. We will be using Webpack to build our package. In the package.json file paste the following code:

    {
        "main": "src/index.js",
        "scripts": {
            "dev": "node_modules/webpack/bin/webpack.js --progress --config build/webpack.config.js",
            "build": "node build/build.js",
            "build-docs": "node build/build-docs.js",
            "build-main": "node build/build-main.js"
        },
        "dependencies": {
            "vue": "^2.5.13"
        },
        "devDependencies": {
            "babel-core": "^6.22.1",
            "babel-helper-vue-jsx-merge-props": "^2.0.3",
            "babel-loader": "^7.1.1",
            "babel-plugin-syntax-jsx": "^6.18.0",
            "babel-plugin-transform-runtime": "^6.22.0",
            "babel-plugin-transform-vue-jsx": "^3.5.0",
            "babel-preset-env": "^1.3.2",
            "babel-preset-stage-2": "^6.22.0",
            "chalk": "^2.0.1",
            "copy-webpack-plugin": "^4.0.1",
            "css-loader": "^0.28.0",
            "extract-text-webpack-plugin": "^3.0.0",
            "file-loader": "^1.1.4",
            "friendly-errors-webpack-plugin": "^1.6.1",
            "html-webpack-plugin": "^2.30.1",
            "webpack-bundle-analyzer": "^2.9.0",
            "node-notifier": "^5.1.2",
            "postcss-import": "^11.0.0",
            "postcss-loader": "^2.0.8",
            "postcss-url": "^7.2.1",
            "semver": "^5.3.0",
            "shelljs": "^0.7.6",
            "optimize-css-assets-webpack-plugin": "^3.2.0",
            "uglifyjs-webpack-plugin": "^1.1.1",
            "url-loader": "^0.5.8",
            "vue-loader": "^13.3.0",
            "vue-style-loader": "^3.0.1",
            "vue-template-compiler": "^2.5.2",
            "portfinder": "^1.0.13",
            "webpack": "^3.6.0",
            "webpack-dev-server": "^2.9.1",
            "webpack-merge": "^4.1.0"
        }
    }

Next, run the following command to install the dependencies:

    $ npm install

This will install the dependencies we specified above. Take note that these dependencies are the basic requirements for setting up our build system and other components needed for our module.

Next, create a src directory and create a file index.js then paste in the following code:

    import Vue from 'vue'
    import UserPop from './UserPop.vue'

    export default {
        install(Vue, options) {
            Vue.component('user-pop', UserPop)
        }
    }

This file, src/index.js, is the main entry point for our module and it defines it as a plugin. Next we’ll create the user pop component referenced on line 2.

Create a file named UserPop.vue in the src directory. In that file paste in the following code:

    <template>
      <div class="inline" v-if="user">
          <a href="#" class="user-pop" v-on:mouseover="hover" v-on:mouseout="hoverOut">
            {{ main }}
          </a>
          <div class="user-popover" v-if="showPopup" transition="fade" v-on:mouseover="hoverInfo" v-on:mouseout="hoverOutInfo">
            <div class="user-popover--img" v-bind:style="{ backgroundImage: 'url('+user.profile.profile_image+')' }">
              <h3 class="img-inner">{{ user.name }}</h3>
            </div>
            <div class="col-md-12">
              <p>{{ user.username }}</p>
            </div>
            <div class="col-md-12" v-if="user.email">
              <p>{{ user.email }}</p>
            </div>
          </div>
        </div>
    </template>

In the code above we have defined the HTML part of our Vue component. In the same file, paste the following code below the closing template tag:

    <script>
    export default {
        props: ['user', 'main'],
        data() {
            return {
                timer: '',
                isInInfo: false,
                showPopup: false,
            }
        },
        methods: {
            hover: () => {
                this.timer = setTimeout(() => this.showPopover(), 600)
            },
            hoverOut: () => {
                clearTimeout(this.timer);
                this.timer = setTimeout(() => {
                    if ( ! this.isInInfo) {
                        this.closePopover();
                    }
                }, 200);
            },
            hoverInfo: () => this.isInInfo = true,
            hoverOutInfo: () => {
                this.isInInfo = false;
                this.hoverOut()
            },
            showPopover: () => this.showPopup = true,
            closePopover: () => this.showPopup = false,
        }
    }
    </script>

Finally we add some styling using the style tag. Paste the following below the closing script tag:

    <style>
    .user-pop{
      color: inherit;
      text-decoration: none;
    }
    .user-pop:hover{
        text-decoration: none;
        color: inherit;
    }
    .user-popover{
            position: absolute;
            width: 200px;
            background: #fff;
            border: none;
            border-radius: 5px;
            box-shadow: 0 6px 6px rgba(16, 16, 16, 0.04), 0 6px 6px rgba(0, 0, 0, 0.05);
            z-index:999;
            text-align: left;
     }
     .user-popover--img{
      background: rgb(237, 27, 27);
      background-position: center !important;
      background-size: cover !important;
      height: 100px;
      width: 100%;
      padding: 12px;
      text-align:left;
      vertical-align: bottom;
    }
    .user-popover--inner{
      padding: 10px;
    }
    .img-inner{
      color:rgb(237, 27, 27);
      font-size: 17px;
    }
    </style>

Now we have a standalone UI component. Importable into any Vue project. Now let’s build our module using Webpack.

Building our sample module with Webpack

As it is right now, our module can be used without building it. We can also decide to build it into a single JS file so we can include it into an HTML page using the script tag.

Most of what we need to do concerning publishing the module is done with Webpack. For our module, there are two ways we want it to be used, and we will setup webpack configurations for both instances. These are:

  • Browser-based implementation, using the script tag.
  • Node-based implementation.

To do this, we are going to use a common webpack configuration located in the ./webpack.config.js file:

    const webpack = require('webpack');
    const merge = require('webpack-merge');
    const path = require('path');

    var commonConfig = {
      output:{
        path: path.resolve(__dirname + '/dist/')
      },
      module:{
        loaders: [...]
      },
      externals:{...},
      plugins:{...}
    }

    module.exports=[

      // for the browser based implementation
      merge(commonConfig,{

      }),

      // for the node based implementation
      merge(commonConfig, {

      })
    ]

Browser based implementation

Using the plugin file as the base entry point for the application we can specify the output to a file for the browser based implementation, vue-preview.min.js.

Modify the Webpack configuration file to support this using the code below:

    module.exports = [
      [...]

      // browser based implementation
      merge(config, {
        entry: path.resolve(__dirname + '/../src/index.js'),
        output: {
          filename: 'vue-preview.min.js'
        }
      }),

      [...]
    ]

This allows us to import the library via HTML. The build system allows us to have our module available as a min.js file, which we can link to in a script tag. We can also use it via the import statement, importing the entry file (src/index.js)

Exporting as a library

Using the libraryTarget option you can have a plugin accessible to the window object. Paste this in the output option of the webpack.config.js file:

    output: {
      filename: 'vue-preview.min.js',
      libraryTarget: 'window',
      library: 'VuePreview'
    }

With this the module is accessible via the window object using window.VuePreview().

Cleaning up the Package (.json)

To prepare our package is ready for publishing, we need to make sure that our package.json gives information as to what our package does and its entry point. You can copy and paste the JSON code below (everything except the devDependencies section):

    {
      "name": "preview-component",
      "version": "1.0.12",
      "main": "src/index.js",
      "scripts": {
        "dev": "node_modules/webpack/bin/webpack.js --progress --config build/webpack.config.js",
        "build": "node build/build.js",
        "build-docs": "node build/build-docs.js",
        "build-main": "node build/build-main.js"
      },
      "license": "MIT",
      "dependencies": {
        "vue": "^2.5.13"
      },
      "devDependencies": {
        [...]
      }
    }

The most important things to note here are:

  1. The main option which points to the bundled entry file.
  2. The dependencies option that lists the packages needed.

Using the module

So now that our module is complete, here is an example on how we can use it in a Vue application.

First we initalize a vue app using the vue cli tool. If you don’t have it you can install it using the command:

    $ npm install --global @vue/cli

Now you can initialize a Vue project using the command:

    $ vue init webpack sampleapp

💡 Vue-CLI will show some option settings, you can decide to use the defaults or customize as you wish.

Next we proceed to structure our app:
We intend to create a minimalist chat interface with, with the usernames on the right. On hovering over the names the preview modal is supposed to pop up.

First we add the preview-component. At the moment its hosted in GitHub, but can be linked to a project using the git+ssh link as the repository address:

    {
      [...]
      "dependencies": {
        [...]
        "preview-component": "git+https://git@github.com/neoighodaro-articles/Vue-Slack-Preview.git",
        [...]
      },
    }

💡 You should clone the repository and upload the code to GitHub then set as the dependency for your application.

As seen above, we simply added the preview-component to the dependencies option of the package.json file created by Vue CLI. You should run the command below to install the component:

    $ npm install

In the ./app/main.js file add following before the new Vue instance:

    // [...]
    import PreviewComponent from "preview-component";

    // [...]

    Vue.use(PreviewComponent);

    // [...]

In the sample code above, you can see where the package is imported as PreviewComponent.

After it’s imported, it’s linked to the Vue instance with the use method. This makes it available to Vue globally. Next, we create our Chat and Message components. The Chat component will hold the messages which the Message component will use to display messages. The Message component will be using the p``review-component to show a preview of the users profile.

Let’s create the chat component. Create a new file src/components/ChatComponent.vue and paste in the following code:

    <template>
      <div class="chat-main">
        <Message v-for="message in messages" :key="message.username" :message="message"/>
      </div>
    </template>

    <script>
    import Message from './Message'
    export default {
      data(){
        return {
          messages:[
            {
              user: {
                  name: 'Neo Ighodaro',
                  username: 'neoighodaro', 
                  email: 'neo@gmail.com',
                  profile: {
                      profile_image:'https://avatars3.githubusercontent.com/u/807318'
                  },
              },
              message: 'How have you been'
            },
            {
              user: {
                  name: 'Osita Chibuike',
                  username: 'mozartted', 
                  email: 'mozart@gmail.com', 
                  profile: {
                      profile_image:'https://avatars2.githubusercontent.com/u/11639772'
                  },
              },
              message: "I'm alright, This is an article right??"
            },
            {
              user: {
                  name: 'Neo Ighodaro',
                  username: 'neoighodaro',
                  email: 'neo@gmail.com',
                  profile: {
                      profile_image:'https://avatars3.githubusercontent.com/u/807318'
                  },
              },
              message: 'Yea, I think so'
            },
          ]
        }
      },
      components: { 
          Message
      }
    }
    </script>

    <style>
    .chat-main {
      width:500px;
      height: auto;
      box-shadow: 0px 1px 4px #202020;
      border: none;
      padding: 12px;
      margin:0 auto;
    }
    </style>

Next, let’s create the message component. Create a new file src/components/MessageComponent.vue and paste in the following code:

    <template>
      <div class="chat-message">
        <div class="chat-side--bar">
          <user-pop :user="message.user" :main="message.user.name"></user-pop>
        </div>
        <div class="chat-inner--sec">
          {{message.message}}
        </div>
      </div>
    </template>

    <script>
    export default {
      props: ['message'],
      data() {
        return {
        }
      }
    }
    </script>

    <style>
    .chat-message {
      width: 100%;
      border:none;
      box-shadow: 0px 1px 4px #202020;
      padding: 4px;
      min-height: 50px;
      margin-top:12px;
    }
    .chat-side--bar {
      width:20%;
    }
    .chat-inner--sec {
      width: 80%;
    }
    </style>

This component accepts a prop which we use to display the message. The prop also contains the user which contains the user details.

The component then uses the UserPop component which has been defined in the entry file of the imported module to create the preview functionality.

To preview simply run npm run dev and checkout the served URL displayed on the terminal. Here is a sample of it in action:

finished app

Publishing your module to NPM

You can decide to publish your module to NPM if you want it to be available to other developers. Here is a great video that shows how you can do this:

https://youtu.be/BkotrAFtBM0

You can also follow along using the tutorial on NPM’s official website here.

A note on abstraction

External modules make code reuse easier, but their real power is displayed when they have been used from the beginning of a large project.

Consider a series of applications with similar frontend feature sets. For example, Google, and its suite of applications including Gmail, Youtube, Newspaper, Calendar etc. They all have a design standard that makes them similar in many ways. These similar UI features and sections can be abstracted as external modules used by the in-house team to build a generic UI for any of their products.

In order to always maintain the Google standard and style, it’s important to understand when it’s advisable architecture wise to abstract the UI with the intention of creating a developer friendly implementation and environment for building new products.

Many have taken these thought process and created implementations of generic UI elements of some of the most popular apps around. For example https://github.com/airyland/vux, implements most of WeUI components in a smooth style.

Conclusion

This tutorial has shown how easy it is to create external modules with Vue.js, allowing developers to make their frontend components reusable and shareable.

External modules solve a large variety of problems and thus speed up the development process of subsequent applications.

The source code for the module and its sample usage are available on GitHub here and here.