loading...

Vue.js – Chapter 2: Vue Tooling

How to configure WordPress multisite with NGINX

Like the other established frameworks out there, a collection of tooling has sprung up around Vue. By tooling, I’m referring to software whose job is to facilitate the development of applications (such as code generation), prepare it for release or deployment (for example, compilation and packaging), or facilitate debugging when the inevitable bugs creep in.

In this chapter, I’d like to focus on the latter two of these categories—build tooling, and debugging. Both are well served by official Vue tools, which we’ll be taking a look at.

Why Use Build Tooling?

While including Vue from a CDN can be a good option when you’re just starting out, or when you’re whipping up a quick proof-of-concept app, we’ll want to introduce some build tools to assist us in producing modern, modular, and efficient JavaScript that’s ready for production.

Having a good build tooling setup will pay dividends by automating much of the work of preparing your code for deployment. Not only that, but it ensures the process is reliable and repeatable and removes the opportunity for human error (for example, forgetting to perform a step in a manual process).

Let’s take a brief look at some of the most common tasks handled by modern build tooling.

Transpilation: Using Modern JavaScript Syntax in Old Browsers

The newer syntax and features (> ES2015) facilitate more concise, readable code, as well as making JavaScript a more pleasant language to develop in. Even though all modern browsers now support ES2015 (aka ES6), you don’t always have the luxury of ignoring older browsers.

By adding a build step with Babel, you can transpile your code back to an older version (including some polyfills where necessary) and support older browsers without having to give up the modern language features.

As a bonus, by introducing transpilation we can also adopt more cutting-edge features before they’ve gained widespread browser support!

Linting: Ensuring Code Quality

A must-have tool for serious JavaScript developers these days is the code linter. A linter can be run during development and/or during a build step, scanning your code for syntax errors as you type. Many popular code editors and IDEs can be configured to display these errors as you type, giving you real-time feedback and helping to prevent bugs from creeping into your code.

ESLint, one of the most popular linters, can also be configured to check if your code conforms to pre-defined sets of rules for coding conventions and even code style preferences. There’s even an official Vue plugin for ESLint (eslint-plugin-vue, discussed below), which will help you produce idiomatic code that adheres to recommended best practices.

Using Single-file Components

One major benefit of introducing a build step is that you can also start using Vue’s single-file components (SFCs) within your application. SFCs allow you to combine the template, code, and styling for a component within a single file with a .vue extension.

The advantages of keeping the logic and UI for a component together in the same file are twofold: the components are easier to maintain, as all the necessary parts are kept together and not spread out through the file system; and because each component is self-contained, the code is much easier to reuse in other projects.

ExampleComponent.vue

<template>
  <div >{{ msg }}</div>
</template>

<script>
export default {
  data () {
    return {
      msg: 'Hello world!'
    }
  }
}
</script>

<style>
.example {
  color: red;
}
</style>

Using the vue-loader webpack plugin, the HTML inside the <template> tags is compiled to JavaScript code that’s minified and bundled into your application, along with the component JavaScript from within the <script> tags.

<style> tags can be used to include style rules in CSS, or a number of other formats (specified by a lang attribute). These are extracted by the plugin and piped through other CSS rules you’ve set up in your webpack configuration. By adding the scoped attribute to the tag, the resulting styles will be identified by a unique hash, preventing them from affecting any other components in the app.

Minification: Saving Space (and User Bandwidth)

While including libraries and script files via individual <script> tags is fine for simpler use cases, for production code you’ll want to be optimizing your application to make the best use of your users’ bandwidth and provide an optimal experience.

In the case of Vue, building the code for production provides a performance benefit: your templates are compiled down to JavaScript, meaning that your application no longer needs to include the template compiler as part of the bundled code.

Vue CLI

The average client-side JavaScript project will utilize a range of build tools including transpilers, linters, minifiers and module bundlers, and each of these tools has its own configuration options that often need to be set a certain way in order to play nicely with the other tools in the chain.

A number of boilerplate projects have sprung up to take the pain out of setting up new apps, by providing a pre-configured starting point that you can build on, rather than start from scratch. These can work out well if you’re able find a boilerplate project that includes the set of tools you want to use.

Vue’s CLI (command-line interface) is a terminal-based tool that aims to solve this problem in a different way, allowing you to create new projects by selecting preset combinations, or picking and choosing the build tools you want and having the CLI install and configure them for you.

Installing the CLI

Installing the CLI tool is very straightforward, and you probably won’t be surprised to learn that it’s done via npm. We’ll be using version 3, which was recently released at the time of writing. It’s installed with the following command:

npm install -g @vue/cli

The above will install Vue CLI as a global module, meaning you can access it from any directory on your system directly from your terminal/command prompt.

Prerequisites

You’ll need Node/npm and Git installed to be able to use Vue CLI. I recommend using nvm to install and manage Node.js on your system.

Setting up New Projects

To start a new Vue project from the terminal you use the vue create command, followed by the name of the project:

vue create my-new-project

This command will create a folder in the current directory with the name of the project you provided. After pressing enter, an interactive prompt will launch and allow you to choose between starting from a preset or manually selecting features.

On a fresh install of the CLI, the only preset available is default (babel, eslint), which will set up your project with transpilation and code linting, which includes the “essential” Vue ruleset.

If you choose a preset, Vue CLI will then set up your project folder as a local Git repository, create a skeleton application structure, and run npm install under the hood to pull in any dependencies.

Automatic Project Source Control

The CLI will not only initialize your project folder as a Git repo but will make the first commit for you. This means that you’re free to start experimenting right away, and can easily revert to your original state by running git reset --hard.

Once it’s finished, you should be left with something like this:

├── babel.config.js
├── node_modules (omitted for brevity)
├── package.json
├── package-lock.json
├── public
│   ├── favicon.ico
│   └── index.html
├── README.md
└── src
    ├── App.vue
    ├── assets
    │   └── logo.png
    ├── components
    │   └── HelloWorld.vue
    └── main.js

After changing into the new project directory, there are several npm scripts pre-configured that you can use:

  • npm run serve. This will start a local development server and compile the project files. The process will watch the files in your src folder and recompile on any changes.
  • npm run build. This command will compile your project, creating an optimized production build.
  • npm run lint. This will run the linter on your source files, checking them for compliance with the rulesets specified in the eslintConfig section of the project’s package.json file.

The generated package.json file is also worth a quick look:

{
  "name": "my-new-project",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "vue": "^2.5.17"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "^3.0.1",
    "@vue/cli-plugin-eslint": "^3.0.1",
    "@vue/cli-service": "^3.0.1",
    "vue-template-compiler": "^2.5.17"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/essential",
      "eslint:recommended"
    ],
    "rules": {},
    "parserOptions": {
      "parser": "babel-eslint"
    }
  },
  "postcss": {
    "plugins": {
      "autoprefixer": {}
    }
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not ie <= 8"
  ]
}

As you can see, ESLint has been set up with the recommended ruleset, and the vue/essential plugin (which you can read more about in the ESLint plugin’s repo. Babel has also been configured to support all the browsers covered by the broswerslist options.

While the default preset is a good starting point for learning about build tooling in Vue apps, and for building quick prototypes, for proper applications you’re probably going to want to customize the project by selecting the features you want.

Webpack Configuration

Vue CLI is built on top of webpack but abstracts away all the configuration to make it easier to get up and running. You can see the webpack configuration at any time by running the vue inspect command.

Running Vue CLI and choosing to manually select features presents you with the following screen:

Plugins

Let’s take a look at the available plugins.

  • Babel. As in the “default” preset, this will set up your project to transpile ES2015+ code back to JavaScript ES5 for wider browser compatibility.
  • TypeScript. This sets up the TypeScript compiler, so you can write your code with the benefit of static typing.
  • Progressive Web App (PWA) Support. This plugin will add all of the boilerplate files necessary to create an installable PWA with custom icons and offline support. We’ll take a closer look at PWAs later in the book.
  • Router. If you need client-side routing, this option will pre-install the official Vue Router library. We’ll be looking into routing in Vue apps in Chapter 4.
  • Vuex. This option will set up your project with Vuex, which is the official state management solution for more complex Vue apps. We’ll dive deeper into Vuex in Chapter 5.
  • CSS Pre-processors. Selecting this option will lead to a further screen allowing you to choose from SCSS/Sass, LESS, and Stylus plugins. Note that by default, Vue CLI supports PostCSS, Autoprefixer and CSS Modules.
  • Linter / Formatter. This option will give you the choice of installing ESLint by itself, or in combination with the Airbnb config, Standard config, or the Prettier code formatter.
  • Unit Testing. Selecting unit testing will give you the option to install Mocha and Chai, or Jest as your testing tools.
  • E2E Testing. Similarly to the unit testing option, choosing E2E testing will let you choose between installing Cypress and Nightwatch.

After you’ve made your selections, the CLI will ask you how you want to store your configuration options (in separate files, or in package.json) and then allow you to save your current plugin selection as a preset for future use.

You can also add plugins to existing projects that were generated with the CLI tool. This is a big plus point for Vue CLI, as you’re not locked into the choices you make when starting a project and, unlike create-react-app (for example), you don’t have to “eject” from the tool in order to customize your project’s configuration.

From within the project directory, simply run the vue add command with the name of the plugin:

vue add @vue/cli-plugin-typescript
# or
vue add @vue/typescript

The two commands above are equivalent and will both install the TypeScript plugin. Vue CLI automatically expands the shorthand version for you.

It’s also possible to install third-party CLI plugins by omitting the @vue prefix. The following command will install the unofficial Apollo plugin:

vue add apollo

The official Vue CLI plugins are listed in the documentation at cli.vuejs.org, but there’s currently no list of third-party plugins.

Browser Devtools

As I mentioned at the start of the chapter, Vue also has tooling to aid with debugging, in the form of the Vue devtools. The devtools are available as a browser plugin for both Chrome and Firefox, and as a cross-platform Electron app, which can also debug Vue apps running on mobile devices.

If you’ve developed applications with React before, the Vue devtools combine functionality similar to that of the React and Redux extensions.

The tools allow you to take a look into a running Vue application, providing three different tabs to help you inspect and debug your code.

I recommend installing one of the browser extensions (you can find the links on GitHub) and trying the devtools with the examples from this book.

Components Tab

The first section gives you a hierarchical view of all the components that make up your application. Selecting a component from the tree allows you to inspect its state (that is, its data object) in the right-hand pane, where the values can be dynamically edited while the app runs.

When a component is selected, it’s also then available to interact with programmatically from the browser’s console, assigned to the variable $vm0. You can read and write to data values, and call any of the component’s methods.

We’ll revisit this tab in our next chapter on components.

Vuex Tab

This tab is only active if a Vuex store is detected in the application. It allows you to examine the state of the store at any point in time, and all the mutations that have been committed. You can even move back and forth through the mutations, effectively time-traveling through the state of your application.

If this isn’t making much sense to you right now, don’t worry; we’ll be covering Vuex in a later chapter.

Events Tab

The events tab aggregates all the events emitted by your application, from anywhere in the component tree. Selecting an event will display more information about it in the right-hand pane, allowing you to see which component emitted it and any payload that was sent.

Editor/IDE Integrations

Due to its popularity, there are also Vue plugins and extensions available for many of the popular code editors and IDEs. These can offer anything from syntax highlighting for .vue files to autocompletion and code generation.

One of the most fully featured plugins currently available is the Vetur extension for Visual Studio Code (VS Code). As well as syntax highlighting and autocompletion, it provides snippets for scaffolding common tasks (such as new components), code formatting support, debugging, and autocomplete support for popular libraries such as Vue Router, and Vuetify.

Installing Vetur for VS Code

  1. Fire up VS Code and go to the Extensions menu on the left sidebar.
  2. Into the search bar, type “vetur”.
  3. Select the Vetur extension (by Pine Wu) from the results, and hit the install button.

Summary

In this chapter, we looked at the benefits of introducing a build step to your Vue applications, and how you can easily install and configure the necessary build tools for new projects using the Vue CLI.

We also looked briefly at the Vue devtools, which are a must-have resource when working with Vue applications. If you haven’t already done so, I recommend installing them now, as we’ll be using them in the next chapter as we take a look at components.

Comments are closed.

loading...