The Beginner's Guide to Static Site Generators

The Beginner's Guide to Static Site Generators

In this article, I’m going to list five popular static site generators and their main features, so that you can form a better idea of which one among them would be a good fit for your project.

In this article, I’m going to list five popular static site generators and their main features, so that you can form a better idea of which one among them would be a good fit for your project.

Let’s say your next project is going to be a simple HTML website for a resumé, marketing a product or service, documenting your software, or something along those lines. A great option for you is to build your **website **using static site generators (SSG).

There are tons of static site generators in a range of programming languages, such as JavaScript, Ruby, Go — the list goes on.

I’m not claiming that I’ve provided the definitive list of **SSGs **or that I personally favor any of the software I include in my list over any other that’s available out there. However, all of the products in the list are popular, performant, well-documented and well-supported.

What Are Static Site Generators?

A common **CMS **(Content Management System), like WordPress for instance, builds the web page dynamically as it is being requested by the client: it assembles all the **data **from the database, and **processes **the **content **through a template engine.

On the other hand, a static site generator:

takes a different approach and generates all the pages of the website once when there’s actually changes to the site. This means there’s no moving parts in the deployed website. Caching gets much easier, performance goes up and static sites are far more secure. – StaticGen.
If you’re curious and would like to learn more, this great article by Brian Rinaldi looks closely at the inner workings of static site generators.

Now, let’s go through some options.

1. Hugo

Hugo is a very popular static site generator with over 32,000 stars on **GitHub **right now. It is written in Go, and advertises itself as being the fastest framework for building websites. In fact, **Hugo **comes with a fast build process, which makes building static websites a breeze and works great for **blogs **with lots of posts.

The docs are great and the Hugo website offers a fantastic quickstart guide that gets you up and running with the software in no time.

Here are some of Hugo’s best features:

  • Designed and optimized for speed: as a rule of thumb, each piece of content renders in about 1 millisecond
  • No need to install extra plugins for things like pagination, redirection, multiple content types, and more
  • Rich theming system
  • Shortcodes available as an alternative to using Markdown
  • Since July 2018, Hugo offers a powerful assets pipeline, Hugo Pipes.
2. Next.js

Next is a versatile framework for the creation of server-rendered or statically exported JavaScript apps. It’s built on top of **React **and is created by Zeit.

To install Next, run the following command in your terminal:

    npm install --save next react react-dom

Then add this script to your package.json file:

    {
      "scripts": {
       "dev": "next",
       "build": "next build",
       "start": "next start"
      }
    }

With this in place, every .js file becomes a route which gets processed and rendered automatically.

Next.js has great docs, where you can learn more about building and customizing your Next-based apps.

Here are a few things Next is very good at:

  • Next renders on the server by default, which is great for performance. For a discussion of the pros and cons of server-side rendering, check out this article by Alex Grigoryan on Medium
  • No setup necessary: automatic code-splitting, routing and hot reload out of the box
  • Extensibility: feel free to customize your setup by taking control of Webpack and Babel, routing and plugins
  • Great docs, tutorials, quizzes and examples to get you up and running from beginner to advanced user
  • Official and community plugins available
  • Tons of example apps to get you started.
3. Gatsby

Gatsby works great for documentation and blogs, it’s built in **React **and leverages GraphQL for manipulating data. If you’re curious and want to delve deeper, check out How to Build Your Static Site with Gatsby and the docs on the Gatsby website.

Here are some of Gatsby’s strong points:

  • With Gatsby you get to work with the latest web technologies. React, Webpack, modern JS, CSS, etc. all ready for you to just start coding your site
  • Gatsby’s rich plugin ecosystem allows you to use any kind of data you prefer from one or more sources
  • Easy deployment and scalability, which is mainly due to the fact that Gatsby builds static pages, which don’t require complicated setups
  • Gatsby is a Progressive Web Apps (PWA) generator. “You get code and data splitting out-of-the-box. Gatsby loads only the critical HTML, CSS, data, and **JavaScript **so your site loads as fast as possible. Once loaded, Gatsby prefetches resources for other pages so clicking around the site feels incredibly fast.” (Gatsby website)
  • Plenty of starter sites are available for you to grab freely and customize.

Check out our tutorial that shows you how to build your first static site with Gatsby.

4. Nuxt.js

Nuxt.js is a higher level framework built with Vue.js that lets you build production-ready web apps. With Nuxt you can choose among:

  • Server-side rendering for your website, also called universal or isomorphic mode. Nuxt uses a Node server to deliver HTML based on Vue components
  • Static site generation. With Nuxt you can build static websites based on your Vue application
  • Single Page Apps (SPAs). Nuxt gives you the configuration and the framework to build your Vue-based SPA.

Creating Nuxt-based websites can be done super quickly. Here’s the Hello World example on the Nuxt website. You can download it on your machine or play with it on Codesandbox to get started.

Here are some of Nuxt.js’s features:

  • Great performance: Nuxt-based apps are optimized out of the box
  • Modular: Nuxt is built using a powerful modular structure. There are more than 50 modules you can choose from to speed up your development experience
  • Relatively easy learning curve. Nuxt is based on Vue, which is a framework that makes it quick and painless to get started
  • Integrated state management with Vuex
  • Automatic Code Splitting
  • ES6/ES7 Transpilation
  • Bundling and minifying of JS & CSS
  • Managing <head> element (<title>, <meta>, etc.)
  • Pre-processor: Sass, Less, Stylus, etc.
5. VuePress

VuePress is a Vue-powered static site generator. Its default theme is optimized for writing technical docs, therefore it works great for this type of site right out of the box.

A **VuePress **site works as a Single Page App (SPA) that leverages the power of Vue, Vue Router and Webpack.

To install VuePress globally, just run this command in your terminal:

    npm install -g vuepress

Then, to create a markdown file, run:

    echo '# Hello VuePress' > README.md

To start writing, run:

    vuepress dev

To build your site, run:

    vuepress build 

Here are some great features that VuePress has to offer:

  • Setting up your VuePress-based site is quick and you can write your content using Markdown
  • VuePress is built on Vue, which means that you can enjoy the web experience of Vue, Webpack, the possibility of using Vue components inside Markdown files and of developing custom themes with Vue
  • Fast loading experience: VuePress static sites are made of pre-rendered static HTML and run as a SPA once they’re loaded in the browser
  • Multilanguage support by default with i18n. Setting up other languages is also quite straightforward by adding a locales object to the themeConfig object inside your VuePress-based project’s config.js file.

Nuxt.js or VuePress?

Both Nuxt.js and **VuePress **are built on top of Vue.js and let you create static websites. So, which one is to be preferred over the other?

Let’s say that Nuxt.js can do everything VuePress does. However, in essence, Nuxt is best suited for building applications. VuePress, on the other hand, is ideal for creating static documentation websites that display content written in Markdown. A discussion on the project’s GitHub repo is being carried out in view of making VuePress also suited for feature-rich blogging sites. To learn more about how you can set up a simple blog with VuePress, head over to Creating a Blog with VuePress by Adam Collier.

In short, if all you need is a documentation site or a very simple blog in Vue.js, consider reaching out for VuePress — Nuxt would be overkill.

How to Choose a Static Site Generator

With all the options available, it’s easy to feel paralyzed when it comes to choosing a static site generator that fits the bill. There are some considerations that could help you sieve through what’s on offer.

Your project’s requirements should throw some light on the features you should be looking for in your SSG.

If your project needs lots of dynamic capabilities out of the box, then Hugo and Gatsby could be a good choice. As for build and deploy time, all of the SSGs listed above perform very well, although Hugo seems to be the favorite, especially if your website has a lot of content.

Is your project a blog or a personal website? In this case, Hugo and Gatsby could be excellent choices, while for a simple documentation website VuePress would be a great fit. If you’re planning an e-commerce website, then you might want to consider which SSG fits in well with a headless CMS for store management. In this case, Gatsby and Nuxt could work pretty well.

One more thing you might want to consider is your familiarity with each of the SSG languages. If you program in Go, then Hugo is most likely your preferred choice. As for the remaining options, they’re either built on top of React (Next and Gatsby) or Vue (Nuxt and VuePress).

With regard to stuff like great documentation, strong community and support, all of the static site generators I listed figure among the most popular, or rapidly gaining in popularity like VuePress.

Have you used static site generators for a project? Which one? How did you like the experience?

Top Vue.js Developers in USA

Top Vue.js Developers in USA

Vue.js is an extensively popular JavaScript framework with which you can create powerful as well as interactive interfaces. Vue.js is the best framework when it comes to building a single web and mobile apps.

We, at HireFullStackDeveloperIndia, implement the right strategic approach to offer a wide variety through customized Vue.js development services to suit your requirements at most competitive prices.

Vue.js is an open-source JavaScript framework that is incredibly progressive and adoptive and majorly used to build a breathtaking user interface. Vue.js is efficient to create advanced web page applications.

Vue.js gets its strength from the flexible JavaScript library to build an enthralling user interface. As the core of Vue.js is concentrated which provides a variety of interactive components for the web and gives real-time implementation. It gives freedom to developers by giving fluidity and eases the integration process with existing projects and other libraries that enables to structure of a highly customizable application.

Vue.js is a scalable framework with a robust in-build stack that can extend itself to operate apps of any proportion. Moreover, vue.js is the best framework to seamlessly create astonishing single-page applications.

Our Vue.js developers have gained tremendous expertise by delivering services to clients worldwide over multiple industries in the area of front-end development. Our adept developers are experts in Vue development and can provide the best value-added user interfaces and web apps.

We assure our clients to have a prime user interface that reaches end-users and target the audience with the exceptional user experience across a variety of devices and platforms. Our expert team of developers serves your business to move ahead on the path of success, where your enterprise can have an advantage over others.

Here are some key benefits that you can avail when you decide to hire vue.js developers in USA from HireFullStackDeveloperIndia:

  • A team of Vue.js developers of your choice
  • 100% guaranteed client satisfaction
  • Integrity and Transparency
  • Free no-obligation quote
  • Portal development solutions
  • Interactive Dashboards over a wide array of devices
  • Vue.js music and video streaming apps
  • Flexible engagement model
  • A free project manager with your team
  • 24*7 communication with your preferred means

If you are looking to hire React Native developers in USA, then choosing HireFullStackDeveloperIndia would be the best as we offer some of the best talents when it comes to Vue.js.

Nuxt.js: a Minimalist Framework for Creating Universal Vue.js Apps

Nuxt.js: a Minimalist Framework for Creating Universal Vue.js Apps

In this article, you'll learn how we can take advantage of Nuxt.js to build server-rendered JavaScript applications with Vue.js. Learn how to use its generate command to generate static files for our pages, and deploy them quickly via a service like Firebase Hosting.

In this article, you'll learn how we can take advantage of Nuxt.js to build server-rendered JavaScript applications with Vue.js. Learn how to use its generate command to generate static files for our pages, and deploy them quickly via a service like Firebase Hosting.

Universal (or Isomorphic) JavaScript is a term that has become very common in the JavaScript community. It’s used to describe JavaScript code that can execute both on the client and the server.

Many modern JavaScript frameworks, like Vue.js, are aimed at building single-page applications (SPAs). This is done to improve the user experience and make the app seem faster, since users can see updates to pages instantaneously. While this has a lot of advantages, it also has a couple of disadvantages, such as long “time to content” when initially loading the app as the browser retrieves the JavaScript bundle, and some search engine web crawlers or social network robots won’t see the entire loaded app when they crawl your web pages.

Server-side rendering of JavaScript is about preloading JavaScript applications on a web server and sending rendered HTML as the response to a browser request for a page.

Building server-side rendered JavaScript apps can be a bit tedious, as a lot of configuration needs to be done before you even start coding. This is the problem Nuxt.js aims to solve for Vue.js applications.

What Nuxt.js Is

Simply put, Nuxt.js is a framework that helps you build server-rendered Vue.js applications easily. It abstracts most of the complex configuration involved in managing things like asynchronous data, middleware, and routing. It’s similar to Angular Universal for Angular, and Next.js for React.

According to the Nuxt.js docs, “its main scope is UI rendering while abstracting away the client/server distribution.”

Static Generation

Another great feature of Nuxt.js is its ability to generate static websites with the generate command. It’s pretty cool, and provides features similar to popular static generation tools like Jekyll.

Under the Hood of Nuxt.js

In addition to Vue.js 2.0, Nuxt.js includes the following: Vue-Router, Vuex (only included when using the store option), Vue Server Renderer and vue-meta. This is great, as it takes away the burden of manually including and configuring different libraries needed for developing a server-rendered Vue.js application. Nuxt.js does all this out of the box, while still maintaining a total size of 57kB min+gzip (60KB with vuex).

Nuxt.js also uses webpack with vue-loader and babel-loader to bundle, code-split and minify code.

How it works

This is what happens when a user visits a Nuxt.js app or navigates to one of its pages via <nuxt-link>:

  1. When the user initially visits the app, if the [nuxtServerInit](https://nuxtjs.org/guide/vuex-store/#the-nuxtserverinit-action "nuxtServerInit") action is defined in the store, Nuxt.js will call it and update the store.
  2. Next, it executes any existing middleware for the page being visited. Nuxt checks the nuxt.config.js file first for global middleware, then checks the matching layout file (for the requested page), and finally checks the page and its children for middleware. Middleware are prioritized in that order.
  3. If the route being visited is a dynamic route, and a validate() method exists for it, the route is validated.
  4. Then, Nuxt.js calls the asyncData() and fetch() methods to load data before rendering the page. The [asyncData()](https://nuxtjs.org/guide/async-data/ "asyncData()") method is used for fetching data and rendering it on the server-side, while the [fetch()](https://nuxtjs.org/api/pages-fetch/ "fetch()") method is used to fill the store before rendering the page.
  5. At the final step, the page (containing all the proper data) is rendered.

These actions are portrayed properly in this schema, gotten from the Nuxt docs:

Creating A Serverless Static Site With Nuxt.js

Let’s get our hands dirty with some code and create a simple static generated blog with Nuxt.js. We’ll assume our posts are fetched from an API and will mock the response with a static JSON file.

To follow along properly, a working knowledge of Vue.js is needed. You can check out Jack Franklin’s great getting started guide for Vue.js 2.0 if you’re new to the framework. I’ll also be using ES6 Syntax, and you can get a refresher on that here: sitepoint.com/tag/es6/.

Our final app will look like this:

The entire code for this article can be seen here on GitHub, and you can check out the demo here.

Application Setup and Configuration

The easiest way to get started with Nuxt.js is to use the template created by the Nuxt team. We can install it to our project (ssr-blog) quickly using the vue-cli:

vue init nuxt/starter ssr-blog


Once you’ve run this command, a prompt will open and ask you a couple of questions. You can press Return to accept the default answers, or enter values of your own.

Note: If you don’t have vue-cli installed, you have to run *npm install -g @vue/cli* first, to install it.

Next, we install the project’s dependencies:

cd ssr-blog
npm install


Now we can launch the app:

npm run dev


If all goes well, you should be able to visit http://localhost:3000 to see the Nuxt.js template starter page. You can even view the page’s source, to see that all content generated on the page was rendered on the server and sent as HTML to the browser.

Next, we can make some simple configurations in the nuxt.config.js file. We’ll add a few options:

// ./nuxt.config.js

module.exports = {
  /*
   * Headers of the page
   */
  head: {
    titleTemplate: '%s | Awesome JS SSR Blog',
    // ...
    link: [
      // ...
      {
        rel: 'stylesheet',
        href: 'https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.min.css'
      }
    ]
  },
  // ...
}


In the above config file, we simply specify the title template to be used for the application via the titleTemplate option. Setting the title option in the individual pages or layouts will inject the title value into the %s placeholder in titleTemplate before being rendered.

We also pulled in my current CSS framework of choice, Bulma, to take advantage of some preset styling. This was done via the link option.

Note: Nuxt.js uses vue-meta to update the headers and HTML attributes of our apps. So you can take a look at it for a better understanding of how the headers are being set.

Now we can take the next couple of steps by adding our blog’s pages and functionalities.

Working with Page Layouts

First, we’ll define a custom base layout for all our pages. We can extend the main Nuxt.js layout by updating the layouts/default.vue file:

<!-- ./layouts/default.vue -->

<template>
  <div>
    <!-- navigation -->
    <nav class="navbar has-shadow" role="navigation" aria-label="main navigation">
      <div class="container">
        <div class="navbar-start">
          <nuxt-link to="/" class="navbar-item">
            Awesome JS SSR Blog!
          </nuxt-link>
          <nuxt-link active-class="is-active" to="/" class="navbar-item is-tab" exact>Home</nuxt-link>
          <nuxt-link active-class="is-active" to="/about" class="navbar-item is-tab" exact>About</nuxt-link>
        </div>
      </div>
    </nav>
    <!-- /navigation -->

    <!-- displays the page component -->
    <nuxt/>

  </div>
</template>

<style>
  .main-content {
    margin: 30px 0;
  }
</style>


In our custom base layout, we add the site’s navigation header. We use the <nuxt-link> component to generate links to the routes we want to have on our blog. You can check out the docs on [<nuxt-link>](https://nuxtjs.org/api/components-nuxt-link "<nuxt-link>") to see how it works.

The <nuxt> component is really important when creating a layout, as it displays the page component.

It’s also possible to do a couple of more things — like define custom document templates and error layouts — but we don’t need those for our simple blog. I urge you to check out the Nuxt.js documentation on views to see all the possibilities.

Simple Pages and Routes

Pages in Nuxt.js are created as single file components in the pages directory. Nuxt.js automatically transforms every .vue file in this directory into an application route.

Building the Blog Homepage

We can add our blog homepage by updating the index.vue file generated by the Nuxt.js template in the pages directory:

<!-- ./pages/index.vue -->
<template>
  <div>
    <section class="hero is-medium is-primary is-bold">
      <div class="hero-body">
        <div class="container">
          <h1 class="title">
            Welcome to the JavaScript SSR Blog.
          </h1>
          <h2 class="subtitle">
            Hope you find something you like.
          </h2>
        </div>
      </div>
    </section>
  </div>
</template>

<script>
  export default {
    head: {
      title: 'Home'
    }
  }
</script>

<!-- Remove the CSS styles -->


As stated earlier, specifying the title option here automatically injects its value into the titleTemplate value before rendering the page.

We can now reload our app to see the changes to the homepage.

Building the About page

Another great thing about Nuxt.js is that it will listen to file changes inside the pages directory, so there’s no need to restart the application when adding new pages.

We can test this, by adding a simple about.vue page:

<!-- ./pages/about.vue -->
<template>
  <div class="main-content">
    <div class="container">
      <h2 class="title is-2">About this website.</h2>
      <p>Curabitur accumsan turpis pharetra <strong>augue tincidunt</strong> blandit. Quisque condimentum maximus mi, sit amet commodo arcu rutrum id. Proin pretium urna vel cursus venenatis. Suspendisse potenti. Etiam mattis sem rhoncus lacus dapibus facilisis. Donec at dignissim dui. Ut et neque nisl.</p>
      <br>
      <h4 class="title is-4">What we hope to achieve:</h4>
      <ul>
        <li>In fermentum leo eu lectus mollis, quis dictum mi aliquet.</li>
        <li>Morbi eu nulla lobortis, lobortis est in, fringilla felis.</li>
        <li>Aliquam nec felis in sapien venenatis viverra fermentum nec lectus.</li>
        <li>Ut non enim metus.</li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  head: {
    title: 'About'
  }
}
</script>


Now, we can visit http://localhost:3000/about to see the about page, without having to restart the app, which is awesome.

Showing Blog Posts on the Homepage

Our current homepage is pretty bare as it is, so we can make it better by showing the recent blog posts from the blog. We’ll do this by creating a <posts> component and displaying it in the index.vue page.

But first, we have to get our saved JSON blog posts and place them in a file in the app root folder. The file can be downloaded from here, or you can just copy the JSON below and save in the root folder as posts.json:

[
    {
        "id": 4,
        "title": "Building universal JS apps with Nuxt.js",
        "summary": "Get introduced to Nuxt.js, and build great SSR Apps with Vue.js.",
        "content": "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>",
        "author": "Jane Doe",
        "published": "08:00 - 07/06/2017"
    },
    {
        "id": 3,
        "title": "Great SSR Use cases",
        "summary": "See simple and rich server-rendered JavaScript apps.",
        "content": "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>",
        "author": "Jane Doe",
        "published": "17:00 - 06/06/2017"
    },
    {
        "id": 2,
        "title": "SSR in Vue.js",
        "summary": "Learn about SSR in Vue.js, and where Nuxt.js can make it all faster.",
        "content": "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>",
        "author": "Jane Doe",
        "published": "13:00 - 06/06/2017"
    },
    {
        "id": 1,
        "title": "Introduction to SSR",
        "summary": "Learn about SSR in JavaScript and how it can be super cool.",
        "content": "<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>",
        "author": "John Doe",
        "published": "11:00 - 06/06/2017"
    }
]


Note: Ideally the posts should be retrieved from an API or resource. For example, Contentful is a service that can be used for this.

Components live in the components directory. We’ll create the <posts> single file component in there:

<!-- ./components/Posts.vue -->
<template>
  <section class="main-content">
    <div class="container">
      <h1 class="title has-text-centered">
        Recent Posts.
      </h1>
      <div class="columns is-multiline">
        <div class="column is-half" v-for="post in posts" :key="post.id">
          <div class="card">
           <header class="card-header">
            <p class="card-header-title">
              {{ post.title }}
            </p>
          </header>
          <div class="card-content">
            <div class="content">
              {{ post.summary }}
              <br>
              <small>
                by <strong>{{ post.author}}</strong>
                \\ {{ post.published }}
              </small>
            </div>
          </div>
          <footer class="card-footer">
            <nuxt-link :to="`/post/${post.id}`"
              class="card-footer-item">
              Read More
            </nuxt-link>
          </footer>
        </div>
      </div>
    </div>
  </div>
</section>
</template>

<script>
  import posts from '~/posts.json'

  export default {
    name: 'posts',
    data () {
      return { posts }
    }
  }
</script>


We import the posts data from the saved JSON file and assign it to the posts value in our component. We then loop through all the posts in the component template with the v-for directive and display the post attributes we want.

Note: The *~* symbol is an alias for the */* directory. You can check out the docs here to see the different aliases Nuxt.js provides, and what directories they’re linked to.

Next, we add the <posts> component to the homepage:

<!-- ./pages/index.vue -->
<template>
<div>
    <!-- ... -->
    <posts />
</div>
</template>

<script>
import Posts from '~/components/Posts.vue'

export default {
  components: {
    Posts
  },
  // ...
}
</script>


Adding Dynamic Routes

Now we’ll add dynamic routes for the posts, so we can access a post for example with this URL: /post/1.

To achieve this, we add the post directory to the pages directory and structure it like this:

pages
└── post
    └── _id
        └── index.vue


This generates the corresponding dynamic routes for the application like this:

router: {
  routes: [
    // ...
    {
      name: 'post-id',
      path: '/post/:id',
      component: 'pages/post/_id/index.vue'
    }
  ]
}


Updating the single post file:

<!-- ./pages/post/_id/index.vue -->
<template>
  <div class="main-content">
    <div class="container">
      <h2 class="title is-2">{{ post.title }}</h2>
      <div v-html="post.content"></div>
      <br>
      <h4 class="title is-5 is-marginless">by <strong>{{ post.author }}</strong> at <strong>{{ post.published }}</strong></h4>
    </div>
  </div>
</template>

<script>
  // import posts saved JSON data
  import posts from '~/posts.json'

  export default {
    validate ({ params }) {
      return /^\d+$/.test(params.id)
    },
    asyncData ({ params }, callback) {
      let post = posts.find(post => post.id === parseInt(params.id))
      if (post) {
        callback(null, { post })
      } else {
        callback({ statusCode: 404, message: 'Post not found' })
      }
    },
    head () {
      return {
        title: this.post.title,
        meta: [
          {
            hid: 'description',
            name: 'description',
            content: this.post.summary
          }
        ]
      }
    }
  }
</script>


Nuxt.js adds some custom methods to our page components to help make the development process easier. See how we use some of them on the single post page:

  • Validate the route parameter with the validate method. Our validate method checks if the route parameter passed is a number. If it returns false, Nuxt.js will automatically load the 404 error page. You can read more on it here.
  • The asyncData method is used to fetch data and render it on the server side before sending a response to the browser. It can return data via different methods. In our case, we use a callback function to return the post that has the same id attribute as the route id parameter. You can see the various ways of using this function here.
  • As we’ve seen before, we use the head method to set the page’s headers. In this case, we’re changing the page title to the title of the post, and adding the post summary as a meta description for the page.

Great, now we can visit our blog again to see all routes and pages working properly, and also view the page source to see the HTML being generated. We have a functional server-rendered JavaScript application.

Generating Static Files

Next, we can generate the static HTML files for our pages.

We’ll need to make a minor tweak though, as by default Nuxt.js ignores dynamic routes. To generate the static files for dynamic routes, we need to specify them explicitly in the ./nuxt.config.js file.

We’ll use a callback function to return the list of our dynamic routes:

// ./nuxt.config.js

module.exports = {
  // ...
  generate: {
    routes(callback) {
      const posts = require('./posts.json')
      let routes = posts.map(post => `/post/${post.id}`)
      callback(null, routes)
    }
  }
}


You can check here for the full documentation on using the generate property.

To generate all the routes, we can now run this command:

npm run generate


Nuxt saves all generated static files to a dist folder.

Deployment on Firebase Hosting

As a final step, we can take advantage of hosting by Firebase to make our static website live in a couple of minutes. This step assumes that you have a Google account.

First, install the Firebase CLI, if you don’t already have it:

npm install -g firebase-tools


To connect your local machine to your Firebase account and obtain access to your Firebase projects, run the following command:

firebase login


This should open a browser window and prompt you to sign in. Once you’re signed in, visit https://console.firebase.google.com and click Add project. Make the relevant choices in the wizard that opens.

Once the project is created, go to the project’s hosting page at [https://console.firebase.google.com/project/<project](https://console.firebase.google.com/project/<project "https://console.firebase.google.com/project/<project") name>/hosting and complete the Get started wizard.

Then, on your PC, from the root of your project directory, run the following command:

firebase init


In the wizard that appears, select “Hosting”. Then select your newly created project from the list of options. Next choose the dist directory as the public directory. Select to configure the page as a single-page app and finally select “No” when asked if you want to overwrite dist/index.html.

Firebase will write a couple of configuration files to your project, then put the website live at [https://<project](https://<project "https://<project") name>.firebaseapp.com. The demo app for this article can be seen at nuxt-ssr-blog.firebaseapp.com.

If you run into problems, you can find full instructions on Firebase’s quickstart page.

Conclusion

In this article, we’ve learned how we can take advantage of Nuxt.js to build server-rendered JavaScript applications with Vue.js. We also learned how to use its generate command to generate static files for our pages, and deploy them quickly via a service like Firebase Hosting.

The Nuxt.js framework is really great. It’s even recommended in the official Vue.js SSR GitBook. I really look forward to using it in more SSR projects and exploring all of its capabilities.

10+ Must-Have Tools & Libraries for Vue.js Development

10+ Must-Have Tools & Libraries for Vue.js Development

If you are serious about Vue development, sooner or later you’ll meet some fundamental tools and libraries which stand out from the crowd. Using them will level up your career as a Vue developer, and make you feel like a professional.

If you are serious about Vue development, sooner or later you’ll meet some fundamental tools and libraries which stand out from the crowd. Using them will level up your career as a Vue developer, and make you feel like a professional.

Vue continues to grow in popularity and is rapidly being adopted by many developers, and Vue.js tools are popping up everywhere. This is not without reason: Vue’s shallow learning curve, clear functionality-driven structure, and excellent documentation make it easy for novices to pick it up, and for more experienced developers to make a switch from other frameworks like React or Angular.

I’ve compiled a list of the most notable tools and libraries you should know and eventually use in your Vue.js projects. Unlike many other articles out there, which list only UI component libraries, this compilation explores a much broader mixture of tools, libraries, and plugins in the Vue ecosystem.

I’ve selected these based on their usefulness, effectiveness, and uniqueness — not their GitHub popularity or star ratings.

Enough talk: here they are, the top ten.

Vue CLI

It seems that having some kind of CLI tool is a must for every JavaScript application framework these days. Vue is no exception. Vue CLI is a fully-featured set of tools for rapid Vue development. Besides the usual project scaffolding, it allows you to experiment with new ideas even without creating a full project, by using its instant prototyping feature.

By default, Vue CLI offers support for the major web development tools and technologies, such as Babel, TypeScript, ESLint, PostCSS, PWA, Jest, Mocha, Cypress, and Nightwatch. This is possible thanks to its extensible plugin system. This means the community can build and share reusable plugins for common needs.

But the icing on the cake is the powerful GUI (Vue UI, which comes with the CLI) which allows you to create your project easily, and then configure and manage it along the way without the need for ejection.

Vue CLI

VuePress

The next big player in Vue’s ecosystem is VuePress, a Vue-powered static site generator. Initially created as a tool for writing technical documentation, now it’s a small, compact, and powerful headless CMS. Since version 1.x, it has offered great blogging features and a powerful plugin system. It comes with a default theme (tailored to technical documentation), but you can also build custom themes or use a pre-made option from the community.

In VuePress, you write the content in Markdown, which is then transformed to pre-rendered static HTML files. Once those files are loaded, your site runs as a single-page application powered by Vue, Vue Router and Webpack.

One of the main benefits of VuePress is that you can include Vue code or components within your Markdown files. This gives you great power and flexibility because you can develop your site almost like a regular Vue app, with all benefits that come from that.

VuePress

Gridsome

Gridsome has many similarities with VuePress but it takes a different and very powerful approach when dealing with data sources. It allows you to connect and use many different kinds of data in your app, which are then unified in one GraphQL layer. Basically, Gridsome uses Vue for front-end functionality and GraphQL for data management. The way this works can be summarized in the following three steps:

  1. You provide content in the Markdown, JSON, YAML, or CVS data formats, or import it from a CMS like WordPress or Drupal.
  2. The content is turned into the GraphQL layer, which provides centralized data management. Then you use that data to build your app with Vue.
  3. You deploy pre-rendered HTML files to static web hosts or CDNs such as Netlify, Amazon S3, Now.sh, Surge.sh, etc.

There are some great best practices that Gridsome provides out of the box, such as code splitting, asset optimization, progressive images, and link prefetching. So, Gridsome is fast, and also PWA-ready and SEO-friendly.

Gridsome

Vuex

State management is one of the main problems developers meet in web app building. To solve this, Vue offers a state management system — Vuex. It serves as a centralized store for all the components in an application, where the state can only be mutated predictably. A store is a special object which is divided into four parts:

  • state – an object which stores the app’s data
  • getters – an object containing methods used to abstract the access to the state
  • mutations – an object containing methods that directly affect the state
  • actions – an object containing methods used to trigger mutations and execute asynchronous code

The store can be also divided into modules for better maintainability.

Vuex

Nuxt

When it comes to using server-side rendering (SSR), Nuxt is the usual way to go. It’s a simple and straightforward framework for building universal applications. It’s also modular, so you can use only those modules that you need for your app.

With Nuxt, you can create server-rendered apps (SSR), single-page applications (SPA), progressive web applications (PWA), or just use it as a static site generator.

In brief, Nuxt saves you from the tedious job of structuring and optimizing your app, giving you a streamlined and more enjoyable development experience.

Nuxt

Vuetify

Vuetify is one of the greatest UI component libraries out there. It offers a large set of crafted components (80+) based on the Material Design spec, which is enough for almost any app’s needs.

You can use it to build SSR apps, SPAs, PWAs, and mobile apps. You can start new apps or add them to existing applications. It offers free and premium themes, but you can build your own as well. It also provides a system to pick and choose only the components in use, thus reducing the final size of your app dramatically.

All Vuetify components are very well documented and clear examples are provided.

Vuetify

Quasar

Quasar is the JavaScript version of the “write once, run everywhere” Java philosophy. It’s a universal, Vue-powered framework that allows you to write apps for different platforms with the same code base. SPAs, PWAs, SSR apps, Hybrid Mobile Apps or Multi-platform Desktop Apps, you name it!

It has great documentation and a massive set of components designed with performance and responsiveness in mind. Quasar integrates best practices (HTML/CSS/JS minification, cache busting, tree shaking, source mapping, code-splitting with lazy loading, ES6 transpiling, code linting, accessibility) by default so you can focus primarily on your app’s features. It also provides a CLI tool for effortless scaffolding of new projects.

Quasar

Storybook

Vue is a primarily component-based framework, so writing good, efficient components is crucial for every app developer. In this undertaking Storybook might come in very handy. It allows you to develop, manage, and test UI components in an easy-to-use and isolated environment. The tool enables developers to create components independently from the main app and showcase them interactively in an isolated development environment without worrying about app-specific dependencies and requirements.

Storybook provides plenty of add-ons, plus a flexible API to customize your storybook as you need. You can also export as a static web app and deploy your project to any HTTP server.

Storybook

Vue Apollo

There is a lot of buzz around GraphQL lately. So if you are already familiar with it and want to integrate it with Vue, you should try Vue Apollo. This library makes the use of Vue and GraphQL/Apollo together smooth and pleasant.

Vue Apollo

Eagle.js

Eagle.js is a powerful, flexible and unique slideshow system built with Vue. It allows you to create easy-to-reuse components, slides, and styles across your presentations. It also supports animations, themes, and interactive widgets which are great for making web demos. Eagle.js has a simple and hackable API, so you have the real freedom to craft the slideshows you want.

One of the greatest things you can do with this library is to place a slide in a separate file and then reuse it in other slideshows. You can also import the slides of a particular slideshow inside another one. With such a powerful tool, you can make complex, interactive, and entertaining presentations.

Eagle.js

Bonus: 5 More Notable Vue Tools and Libraries

Here is a little bonus for you: another five tools and libraries which deserve your attention.

  • Vue DevTools is a great browser extension for debugging Vue and Vuex applications.
  • Vue Test Utils is a collection of useful utilities for testing Vue components.
  • Vue Router is the official router for Vue.
  • Vue Native is a JavaScript framework for mobile apps, similar to React Native.
  • Weex is a framework for building mobile apps with modern web technologies, including Vue.
Conclusion

Now you have the tools you need to build awesome projects, no matter what they are: websites, apps, libraries, plugins, the list goes on. Go build something great!