We're live-coding on Twitch! Join us!
Getting Started with Gridsome

Getting Started with Gridsome

Code Demo

The era of Static Site Generators is changing over time, a lot of cool tools are being created to help foster the JAMStack evolution and developers are embracing these tools. One of the tools for creating blazing fast websites is Gridsome.

In this article, we’ll be taking a look at how to use Gridsome to create a sample profile listing site, its major features and how it compares to other Static Sites Generators.

What is a Static Site Generator?

Remember how we used to play around with plain HTML sites with a little drop of CSS here and there I used to do that a lot when I started learning. You will naturally call that site we end up building a static site right because there’s no form of dynamic action going on. This is a true fact but it spans over having a static HTML page rendered. Static Site Generators are a new, hybrid approach to web development that allows you to build a powerful, website locally on your computer but pre-builds the site into static files for deployment.

What is Gridsome?

Gridsome is a Vue-powered static site generator for building blazing fast static websites. It is data-driven meaning it uses a GraphQL layer to get data from different sources in order to dynamically generate pages from it. Gridsome is the Vue alternative to Gatsby for React.js.

Homepage of Gridsome

Features of Gridsome

features of gridsome

Gridsome ships with a lot of great features that makes building a static site with Gridsome a great choice. Some of the features it offers includes:

  • Hot-reloading development - See changes in real-time while developing.
  • Vue.js for front-end - Ultra lightweight and approachable front-end framework.
  • GraphQL data layer - Centralized data management for all your data.
  • Automatic page routing - Quickly create and manage pages with files.
  • Progressive image support - Auto resize, optimize & lazy load images.
  • Auto page prefetching - Pages are loaded in the background for fast browsing.
  • Auto optimized code - Get code-splitting and asset optimization out-of-the-box.
  • Fast static page generating - Deploy securely and fast to any Static Web Host.
  • Data source plugins - Add data from popular Headless CMSs, APIs or Markdown-files.

How Gridsome Works?

Essential Reading: Learn React from Scratch! (2019 Edition)

Gridsome is a website framework that enables us to create fast blazing static sites and how it works is it fetches data from data sources like CMSs, local files or external APIs and store the data in a local database. GraphQL acts as a centralized data management system that manages the data and gives you the ability to extract and use data within your vue components. For development, Gridsome provides a command gridsome develop that starts the local server with hot-reloading and a GraphQL data layer. And for production, the gridsome build command prepares the site for production by bundling and generating HTML files that can be hosted and deployed to any global CDN or FTP.

Comparison with Other Static Site Generators

Along with Gridsome, there are other Static Site Generators available to create your website. I’ll compare Gridsome alongside some other Static Site Generator like Gatsby, Nuxt, Vuepress.

Table showing features of static site generators

Building a Gridsome Site

Prerequisite

In order to follow this tutorial, You’ll need to have the following setup:

  • Node v8.0 or higher
  • NPM (this comes packaged with Node) or Yarn.
  • Basic knowledge of JavaScript and Vue

Installing Gridsome

The first thing we’ll do is to check that Node and npm is installed.

node --version && npm -v

Then, you can install Gridsome CLI by running the following command:

yarn global add @gridsome/cli
// or
npm install --global @gridsome/cli

Next step is to create a new project using the CLI we just installed:

gridsome create gridsome-site

Once that is done installing we can run the Gridsome site with this command:

 cd gridsome-site && gridsome develop

Voila! There you have it, your gridsome site is up and running on port 8080. Gridsome also provides a GraphQL playground environment for testing out queries. And you’ll find it running at http://localhost:8080/___explore.

Folder Structure

We’ll be exploring the folder structure of a gridsome site. In order to fully grasp what Gridsome can do we need to fully understand what each file within the project is specifically used for.

.
├── package.json
├── gridsome.config.js
├── gridsome.server.js
├── static/
└── src/
    ├── main.js
    ├── layouts/
    │   └── Default.vue
    ├── pages/
    │   ├── Index.vue
    │   └── Blog.vue
    └── templates/
        └── BlogPost.vue

Gridsome starter comes fully baked with all the files we need for developing a site, we can see there are already a couple of files in the project directory.

  • package.json - This is where all the dependencies for the project will be stored.
  • gridsome.config.js - This file serves as a configuration file for the gridsome site where you configure plugins.
  • gridsome.server.js: This file is optional and is used to hook into various parts of the Gridsome server.
  • /src directory: This folder is where most of the code lives, we have:
    • main.js - This file contains the application configuration such that it plugs in other parts of the app into the gridsome API.
    • Layouts/ - Layout components are used to wrap pages and templates. The layout component is located in the src/layouts folder and should be indicated as the global component. It also requires a slot component which inserts the content of pages and template components into the layout.
    • Pages/ - The pages are individual components, every component in the pages directory becomes a page on the website. Each page will get its path based on the .vue file location. i.e src/pages/Index.vue will become the homepage and src/pages/about will be rendered as the about page.
    • Templates/ - Templates are used for single post views to GraphQL collections. To add a template create .vue file with the same name as a GraphQL collection to src/templates.
  • /static directory: This directory can be used to store files that will be copied directly to the dist/ folder after the build for example /static/robot.txt.Plugins

With Plugins enabled you can have additional functionalities tied to your Gridsome App. Plugins options are added to gridsome.config.js. In this tutorial, we’ll be building a profile listing site and we will need the gridsome/source-faker plugin to help populate data to the site. Let’s go ahead and set that up.

Plugins

With Plugins enabled you can have additional functionalities tied to your Gridsome App. Plugins options are added to gridsome.config.js. In this tutorial, we’ll be building a profile listing site and we will need the gridsome/source-faker plugin to help populate data to the site. Let’s go ahead and set that up.

Install the plugin using the command:

yarn add @gridsome/source-faker 
or 
npm install @gridsome/source-faker

And add the following to the gridsome.config.js file.

module.exports = {
  siteName: 'Fancy Random Profile',
  siteUrl: '',
  siteDescription: 'A directory listing of random profiles',
  plugins: [
    {
      use: '@gridsome/source-faker',
      options: {
        numNode: 50
      }
    }
  ]
}

Setup Bulma for Styling

In this tutorial, I'll be using Bulma for styling and in order to set it up I'll have to add the following lines in main.js file. I'm using Bulma CDN all I need to do is that the link to the head of the generated html file.

import DefaultLayout from '~/layouts/Default.vue'

export default function (Vue, {router, head, isClient}) {
  // Set default layout as a global component
  Vue.component('Layout', DefaultLayout)
  head.link.push({
    rel: 'stylesheet',
    href: '//cdnjs.cloudflare.com/ajax/libs/bulma/0.7.2/css/bulma.min.css'
  })
}

Querying data with GraphQL

With Gridsome there are several ways of getting data into your site. Gridsome makes use of GraphQL for data management. Now that we have setup the plugin let’s check out the GraphQL playground and the queries we have access to. Run yarn develop and navigate to http://localhost:8080/\_\_\_explore

There’s a documentation of all queries and we can see the faker and allFaker queries has been added as a result of the gridsome/source-faker plugin we installed. This data will be used to populate the site we’re building. Now let’s create the profile page.

Displaying the Layout Component

The site we’ll be building will require us to create two pages. First one will be a page with a list of all profiles and the other page which will be the About page will contain details about the site. With Gridsome we have the layouts which are used to wrap pages components. So let’s create a layout called Default.vue and add the following code into it.

<template>
  <div class="container">
    <header class="header">
      <g-link class="title is-size-3" :to="{ name: 'home'}">{{ $static.metaData.siteName }}</g-link>
      <g-link class="subtitle is-size-3" :to="{ name: 'about' }">About</g-link>
    </header>
    <slot/>
  </div>
</template>

You can query data from GraphQL in a Layout component using the static-query like this:

<static-query>
query {
  metaData {
    siteName
  }
}
</static-query>

In the Default.vue file we can see the static-query what this does is it enable you plugin in data from GraphQL into your layout component. Now we are fetching the sitename from Metadata query and using it within the template $static.metaData.siteName. Also by passing in <slot /> we are displaying content of the pages component.

Displaying the Pages Component

Now in order to create the page for displaying random profile, we’ll create an Index.vue file within the pages directory. By default the Index.vue become the homepage in this case, we’ll also create an About.vue component.

<template>
  <Layout>
    <div class="content">
      <div class="card" v-for="edge in $page.allFaker.edges" :key="edge.node.id">
        <div class="card-content columns">
        <div class="column is-2">
          <figure class="image is-128x128">
            <img class="is-rounded" :src="edge.node.avatar">
          </figure>
        </div>
        <div class="column">
          <p class="title"> {{ edge.node.author }}</p>
          <p class="subtitle"> <i class="has-text-dark">Contact Email:</i> {{ edge.node.email.src }}</p>
          <p class="subtitle"> <i class="has-text-dark"> Profile: </i> {{ edge.node.title }}</p>
        </div>
        </div>
      </div>
    </div>
  </Layout>
</template>

The page-query is also used for querying data from GraphQL and still does the same thing as static-query only difference is, it is used specifically for Pages and Templates.

<page-query>
query allFaker {
  allFaker (perPage: 10) {
    edges {
      node {
        email,
        author,
        avatar,
        title,
      }
    }
  }
}
</page-query>

And for the About Page, we are not really querying any data from GraphQL all we just have is a text describing what the site is all about.

<template>
  <Layout class="content">
    <p class="title is-4">
      Fancy Random Profile is a website listing random people's profile and details.
    </p>
   <a href="https://github.com/lauragift21/scotch-gridsome">GitHub Repo Available here</a>
  </Layout>
</template>
<script>

Great! We have just completed the profile listing site and here’s what it looks like. You can run yarn develop to start the server.

Deployment

Deploying a gridsome site is usually not a difficult task as tools like Netlify, Zeit Now, GitHub Pages etc are readily available to help out. We’ll be using Netlify to deploy the app we built in this tutorial. To deploy your Gridsome site to Netlify, head over to the Netlify platform and create a new site page, select your project repo from GitHub, GitLab, or Bitbucket and add the following build configuration.

After adding that, click the deploy site button and that should run a build and generate a link to your site. You can check out the profile lisitng site here.

Wrapping Up

In this tutorial, You’ve learned what Gridsome is all about and how to build a static site using Gridsome and also you learned to use its awesome GraphQL layer to query data. Let this not be the end you can explore more by checking out the JAMStack and possibilities of integrating other API to your site using the JAMStack concept.

Like this article? Follow @lauragift21 on Twitter