Book Image

Hands-on Nuxt.js Web Development

By : Lau Tiam Kok
Book Image

Hands-on Nuxt.js Web Development

By: Lau Tiam Kok

Overview of this book

Nuxt.js is a progressive web framework built on top of Vue.js for server-side rendering (SSR). With Nuxt.js and Vue.js, building universal and static-generated applications from scratch is now easier than ever before. This book starts with an introduction to Nuxt.js and its constituents as a universal SSR framework. You'll learn the fundamentals of Nuxt.js and find out how you can integrate it with the latest version of Vue.js. You'll then explore the Nuxt.js directory structure and set up your first Nuxt.js project using pages, views, routing, and Vue components. With the help of practical examples, you'll learn how to connect your Nuxt.js application with the backend API by exploring your Nuxt.js application’s configuration, plugins, modules, middleware, and the Vuex store. The book shows you how you can turn your Nuxt.js application into a universal or static-generated application by working with REST and GraphQL APIs over HTTP requests. Finally, you'll get to grips with security techniques using authorization, package your Nuxt.js application for testing, and deploy it to production. By the end of this web development book, you'll have developed a solid understanding of using Nuxt.js for your projects and be able to build secure, end-to-end tested, and scalable web applications with SSR, data handling, and SEO capabilities.
Table of Contents (26 chapters)
1
Section 1: Your First Nuxt App
5
Section 2: View, Routing, Components, Plugins, and Modules
10
Section 3: Server-Side Development and Data Management
14
Section 4: Middleware and Security
17
Section 5: Testing and Deployment
20
Section 6: The Further Fields

Why use Nuxt?

Frameworks such as Nuxt exist because of the shortcomings of the traditional SPA and the server-side rendering of multi-page applications (MPAs). We can regard Nuxt as a hybrid of server-side rendering MPA and traditional SPA. Hence, it is dubbed "universal" or "isomorphic". So, being able to do server-side rendering is the defining feature of Nuxt. In this section, we will walk you through other prominent features of Nuxt that will make your app development easy and fun. The first feature we'll look at allows you to write single-file Vue components by using a .vue extension in your files.

Writing single-file components

There are a few methods we can use to create a Vue component. A global Vue component is created by using Vue.component, as follows:

Vue.component('todo-item', {...})

On the other hand, a local Vue component can be created using a plain JavaScript object, as follows:

const TodoItem = {...}

These two methods are manageable and maintainable if you're using Vue for a small project, but it becomes difficult to manage for a big project when you have tons of components with different templates, styles, and JavaScript methods all at once.

Hence, single-file components come to the rescue, in which we only use one .vue file for each Vue component. If you need more than one component in your app, then just separate them into multiple .vue files. In each of them, you can write the template, script, and style that relate to that particular component only, as follows:

// pages/index.vue
<template>
<p>{{ message }}</p>
</template>

<script>
export default {
data () {
return { message: 'Hello World' }
}
}
</script>

<style scoped>
p {
font-size: 2em;
text-align: center;
}
</style>

Here, you can see how we have an HTML template that prints the message from the JavaScript script and the CSS style that describes the presentation of the template, all in one single .vue file. This makes your code more structured, readable, and organizable. Sweet, isn't it? This is only made possible by vue-loader and webpack. In Nuxt, we only write components in .vue files, regardless of whether they are components in the /components/, /pages/, or /layouts/ directory. We will explore this in more detail in Chapter 2, Getting Started with Nuxt. Now, we'll look at the Nuxt feature that allows you to write ES6 JavaScript out of the box.

Writing ES2015+

Nuxt compiles your ES6+ code out of the box without you having to worry about configuring and installing Babel in webpack. This means you can write ES6+ code straight away and your code will be compiled into JavaScript that can be run on older browsers. For example, you will see the following destructuring assignment syntax often when using an asyncData method:

// pages/about.vue
<script>
export default {
async asyncData ({ params, error }) {
//...
}
}
</script>

The destructuring assignment syntax is used in the preceding code to unpack the properties from the Nuxt context into distinct variables that we can use for the logic inside the asyncData method.

For more information about the Nuxt context and ECMAScript 2015 features, please visit https://nuxtjs.org/api/context and https://babeljs.io/docs/en/learn/, respectively.

Writing ES6 in Nuxt is only made possible by babel-loader and webpack. There's more than just the destructuring assignment syntax that you can write in Nuxt, including the async function, the await operator, the arrow function, the import statement, and many more. What about the CSS preprocessor? If you write CSS styles with a popular CSS preprocessor such as Sass, Less, or Stylus, but if you are a Sass person and not a Less person, nor a Stylus person, can Nuxt support any of them? The short answer is yes. We'll find out the long answer to this question in the next section.

Writing CSS with a preprocessor

In Nuxt, you can choose your favorite CSS preprocessor to write the styles for your app, whether it is Sass, Less, or Stylus. They are already pre-configured for you in Nuxt. You can check out their configurations at https://github.com/nuxt/nuxt.js/blob/dev/packages/webpack/src/config/base.js. So, you just need to install the preprocessor and its webpack loader in your Nuxt project. For example, if you want to use Less as your CSS preprocessor, just install the following dependencies in your Nuxt project:

$ npm i less --save-dev
$ npm i less-loader --save-dev

Then, you can start writing your Less code by setting the lang attribute to "less" in the <style> block, as follows:

// pages/index.vue
<template>
<p>Hello World</p>
</template>

<style scoped lang="less">
@align: center;
p {
text-align: @align;
}
</style>

From this example, you can see that writing modern CSS styles is as easy as writing modern JavaScript in Nuxt. All you are required to do is install your favorite CSS preprocessor and its webpack loader. We will use Less in this book in the upcoming chapters, but for now, let's find out what other features Nuxt offers.

For more information about these preprocessors and their webpack loaders, please visit the following links:

Even though PostCSS is not a preprocessor, if you want to use it in a Nuxt project, please visit the guide provided at https://nuxtjs.org/faq/postcss-plugins.

Extending Nuxt with modules and plugins

Nuxt was created on top of a modular architecture. This means you can extend it with endless modules and plugins for your app or Nuxt community. This also means you can choose tons of modules and plugins from the Nuxt and Vue communities so that you don't have to reinvent them for your app. The links to these are as follows:

Modules and plugins are simply JavaScript functions. Don't worry about the distinction between them for now; we will get to this in Chapter 6, Writing Plugins and Modules.

Adding transitions between routes

Unlike traditional Vue apps, in Nuxt, you don't have to use the wrapper <transition> element to handle JavaScript animations, CSS animations, and CSS transitions on your elements or components. For example, if you want to apply a fade transition to the specific page when navigating to it, you can just add the transition name (for example, fade) to the transition property of that page:

// pages/about.vue
<script>
export default {
transition: {
name: 'fade'
}
}
</script>

Then, you can just create the transition style in a .css file:

// assets/transitions.css
.fade-enter,
.fade-leave-to {
opacity: 0;
}

.fade-leave,
.fade-enter-to {
opacity: 1;
}

.fade-enter-active,
.fade-leave-active {
transition: opacity 3s;
}

The "fade" transition will apply to the about page automatically when navigating to the /about route. Cool, isn't it? Don't worry if the code or the class names look a bit overwhelming to you at this point; we will look at this transition feature and explore it in more detail in Chapter 4, Adding Views, Routes, and Transitions.

Managing the <head> element

Also, unlike traditional Vue apps, you can manage the <head> block of your app out of the box without installing the additional Vue package that handles it – vue-meta. You just add the data you need for <title>, <meta>, and <link> via the head property to any page. For example, you can manage the global <head> element via the Nuxt config file of your app:

// nuxt.config.js
export default {
head: {
title: 'My Nuxt App',
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: 'My Nuxt app is
about...' }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
]
}
}

Nuxt will convert this data into the HTML tags for you. Again, we will learn about this feature and explore it in more detail in Chapter 4, Adding Views, Routes, and Transitions.

Bundling and splitting code with webpack

Nuxt uses webpack to bundle, minify, and split your code into chunks that can speed up the load time of your app. For example, in a simple Nuxt app with two pages, index/home and about, you will get similar chunks for the client-side:

Hash: 0e9b10c17829e996ef30 
Version: webpack 4.43.0
Time: 4913ms
Built at: 06/07/2020 21:02:26
Asset Size Chunks Chunk Names
../server/client.manifest.json 7.77 KiB [emitted]
LICENSES 389 bytes [emitted]
app.3d81a84.js 51.2 KiB 0 [emitted] [immutable] app
commons/app.9498a8c.js 155 KiB 1 [emitted] [immutable] commons/app
commons/pages/index.8dfce35.js 13.3 KiB 2 [emitted] [immutable] commons/pages/index
pages/about.c6ca234.js 357 bytes 3 [emitted] [immutable] pages/about
pages/index.f83939d.js 1.21 KiB 4 [emitted] [immutable] pages/index
runtime.3d677ca.js 2.38 KiB 5 [emitted] [immutable] runtime
+ 2 hidden assets
Entrypoint app = runtime.3d677ca.js commons/app.9498a8c.js app.3d81a84.js

The chunks that you would get for the server-side will look as follows:

Hash: 8af8db87175486cd8e06 
Version: webpack 4.43.0
Time: 525ms
Built at: 06/07/2020 21:02:27
Asset Size Chunks Chunk Names
pages/about.js 1.23 KiB 1 [emitted] pages/about
pages/index.js 6.06 KiB 2 [emitted] pages/index
server.js 80.9 KiB 0 [emitted] app
server.manifest.json 291 bytes [emitted]
+ 3 hidden assets
Entrypoint app = server.js server.js.map

These chunks and the build information are generated when you use Nuxt npm run build command to build your app for deployment. We will look at this in more detail in Chapter 14, Using Linters, Formatters, and Deployment Commands.

This aside, there are other great features and plugins from webpack that are used by Nuxt, such as static files and asset serving (asset management), hot module replacement, CSS extraction (extract-css-chunks-webpack-plugin), a progress bar while you're building and watching (webpackbar), and so on. For more information, please visit the following links:

These great features from webpack, Babel, and Nuxt itself will make your modern project development fun and easy. Now, let's take a look at the various application types to see why you should or shouldn't use Nuxt when you're building your next web app.