Some parts of this page may be machine-translated.

 

Static Site Generator Guide for Beginners ②

alt

7/1/2021

Static Site Generator Guide for Beginners ②

The world of static sites is evolving beyond HTML, CSS, and sometimes JS, and the advancements in static site generators have greatly contributed to this.

 

Author: Thom Krupa@thomkrupa November 18, 2020

 

3. Gatsby

Last updated: October 27, 2020

 

Gatsby is the most popular static site generator built on top of React.js, the most popular Javascript framework. Kyle Matthews later established Gatsby, Inc. with Sam Baggett, with the mission of "making website creation fun."

 

3-1 Gatsby Story

GatsbyJS was born in 2015 as a simple static site generator and has become the most popular solution in the market over the past five years. Thanks to Gatsby, Jamstack has grown to what it is today.

 

In 2019, Gatsby, Inc. secured $15 million in Series A funding and built Gatsby Cloud, its first commercial product, a CI platform specialized in fast incremental builds. I will talk about this a bit later. First, let me explain the overview of SSG.

 

3-2 Content Mesh

The most common opinion about Gatsby is data fetching. Gatsby creates a GraphQL API internally. This acts as a kind of middleware between the content sources and the frontend templates.

 

 

Gatsby can connect to any popular headless CMS. With a wealth of Gatsby source plugins available, it can be easily connected. You can mesh sources with a single GraphQL query. Everything becomes one large graph.

 

To enjoy the mesh concept, it is necessary to learn GraphQL and the Gatsby API. It may be difficult with a simple static website. Working with GraphQL can be painful, and errors may occur. Debugging is challenging. Some people like it, while others do not.

 

In my opinion, GraphQL API is suitable for unifying and standardizing the way products are created at agencies like ours. Regardless of which CMS you choose, the methods for generating pages and retrieving data are the same.

 

For example, let's take a look at how to retrieve products from Shopify and content from Contentful.

 

  import React from 'react'
import { graphql } from 'gatsby'

const HomePage = ({ data }) => {
return (
<div>
All products:
{data.allContentfulProducts.edges.map(({ node }) => (
<div key={node.id}>
<h2>{node.title}</h2>
</div>
))}
</div>
)
}

export const query = graphql`
query HomePageQuery {
allContentfulProducts(filter: { node_locale: { eq: "en-US" } }) {
edges {
node {
id
slug
title
}
}
}
allShopifyProduct {
edges {
node {
id
title
productType
vendor
variants {
id
title
price
}
}
}
}
}
`


export default HomePage

 

You can retrieve data from anywhere. Headless CMS, local file systems, external GraphQL and REST APIs, Google Spreadsheets, Airtable, and more. You can create your own source plugins for custom integration with the backend.

 

GraphQL queries are executed only at build time. If you change something in the CMS, you need to rebuild the project. Like other React applications, you can also fetch data on the client side. For example, using SWR or even simple fetching will not result in pre-rendering.

 

3-3 File Structure

Below is an example of a file structure.

 

  ├── gatsby-browser.js
├── gatsby-config.js
├── gatsby-node.js
├── gatsby-ssr.js
├── package-lock.json
├── package.json
├── src
│ ├── html.js
│ └── pages
│ ├── 404.js
│ ├── about.js
│ ├── blog.js
│ ├── contact.js
│ └── index.js
└── static
└── logo.png

 

The first four files access the Gatsby API. This means you can modify what Gatsby is doing under the hood. You can add plugins, generate pages from the API, adjust SSR, and manage what happens during the init render in the browser. The official documentation introduces all the features of the API.

 

3-4 Ecosystem

The Gatsby developer community has created thousands of themes, plugins, and starters over the years. Gatsby has the largest ecosystem within Jamstack. The last time I checked the plugin library, there were over 2,400 packages ready to be installed.

 

 

There are people who like plugins and those who do not. However, it is very likely that someone else has the same problem as you and has published a solution.

 

The most popular plugins are gatsby-plugin-react-helmet, gatsby-plugin-sharp, and gatsby-image. There are many plugins like gatsby-plugin-preact that improve page performance. I also talked about Gatsby plugins that were created to solve performance issues before.

 

A large-scale ecosystem enhances the developer experience. In other words, there are already solutions for tedious tasks such as generating sitemaps and adding content security policies.

 

3-5 How to Get Started?

To install Gatsby globally on your computer, run the command.

 

  npm install -g gatsby-cli
  

 

To get started with Gatsby, there are many starters available, so using one of them is the quickest way.

 

To create a project from a starter, select one from the gallery, copy its Github URL, and run it.

 

  gatsby new my-website https://github.com/gatsbyjs/gatsby-starter-default
  

 

To start the Gatsby project locally, execute the following:

 

  cd gatsby-site && gatsby develop
  

 

Your development environment is available at http://localhost:8000.

 

3-6 Development of Gatsby

Gatsby can be deployed anywhere. This is the only command you need to run.

 

  gatsby build
  

 

The Public folder contains all static files that can be publicly shared.

 

If the project contains a small number of GraphQL queries and images, everything will go smoothly. However, with large image sets, such as hundreds of images, it tends to take a very long time to build, and timeout errors may occur with CI/CD tools.

 

If you want to improve build time, the easiest solution is to switch to Gatsby Cloud. It supports fast Incremental Builds and enhances cache management.

 

 

The construction part will be handled by Gatsby Cloud, but to deliver the website to users, it needs to be hosted somewhere. With a typical hosting provider, you can easily connect your project. Gatsby integrates with Netlify, Vercel, Fastly, Google Storage, Azure, Firebase, and AWS S3. Please choose the one that best matches your existing infrastructure.

 

3-7 Conclusion

Gatsby.js is suitable for situations where you want to manage everything using a single internal API while utilizing multiple data sources. Like Next, Gatsby is based on React. It allows for easy creation of interactive components, but this comes with a cost in JavaScript. Client-side routing optimizes perceived performance, especially on high-end devices.

 

It cannot be said to be the lightest static site generator because it requires loading a large amount of JavaScript. While it may be difficult to achieve a perfect score on Lighthouse, that is not always important. You can create a very fast website that provides a pleasant experience for the audience.

 

Features
  • Demonstrates excellent experiential performance through instant route changes and data acquisition
  • A huge ecosystem of themes, plugins, and starters
  • Automatically split code
  • A large community passionate about issues related to Gatsby
  • Incremental Builds and Fast Builds on Gatsby Cloud
  • Integration with all types of content sources is possible
  • The Gatsby team is mindful of accessibility (a18y)
Use Case
  • Marketing site. In particular, if you want to source content from many APIs and leverage the React ecosystem.
  • E-commerce. React is useful for complex forms and product configurators.
  • Pre-rendered static websites and SPAs. Gatsby does not handle dynamic SSR pages, but it is possible to fetch data on the client side just like in other cases.

4. Eleventy

Last updated: October 26, 2020

 

Since Zach Leatherman created Eleventy in 2018, it has gained an increasing number of followers, especially from those who have grown tired of static site generators that heavily use JS. Eleventy is zero-config by default and accommodates any project structure. It supports up to 11 different template languages without being tied to a framework. Eleventy is simple(r). Eleventy adapts to you.

 

Many recent static site generators use some JavaScript frameworks, with React, Vue, and Angular being well-known examples. Eleventy generates static pages using JavaScript. Client-side frameworks are not required.

 

It is not that you should not use any framework. It is an option, and whether to use it or not is up to you.

 

4-1 Progressive Enhancement

JS-based static generation tools like Gatsby and Next.js often face the issue of long Time To Interactive (TTI). The browser needs to download, parse, and execute a large chunk of JS to hydrate the application. This incurs a cost, resulting in delays until the application is interactive.

 

In general websites, many components require hydration even though they are not very interactive. The React team is working on partial hydration to address this issue, but the timeline for completion is unclear.

 

With Eleventy, you can first focus on providing the necessary content and gradually add dynamic features. For creating animations and sliders, sometimes just vanilla JavaScript and pure CSS are sufficient.

 

Need for Speed

Excellent performance is an essential element for any modern website. Developers using Eleventy appreciate this speed. And speed loves Eleventy. Because it doesn't put a heavy load on JavaScript, Eleventy websites achieve great results in Lighthouse. Let's take a look at the leaderboard created by Zach, the author of Eleventy.

 

 

The leaderboard is updated every two weeks, displaying a list of projects that have achieved the best scores. Most of these are very simple personal websites. So, please take this with a grain of salt. This doesn't really mean that Eleventy is the fastest SSG on the market. I believe many of these pages would achieve similar scores with other static site generators as well.

 

4-3 File Structure

A simple thing like that is fine.

 

  └── index.md
  

 

When you run the npx 11ty/eleventy command, it will look like this.

 

  ├── _site
│   └── index.html
└── index.md

 

_site is ready to expand the output folder.

 

Let's create a simple blog. The following example is based on the official eleventy-base-blog starter.

 

  ├── .eleventy.js
├── .eleventyignore
├── _data
│   └── metadata.json
├── _includes
│   ├── components
│   │   ├── footer.njk
│   │   ├── head.njk
│   │   └── header.njk
│   └── layouts
│   ├── base.njk
│   └── post.njk
├── index.njk
└── posts
├── hello-world.md
└── posts.json

 

4-4 Data Sources

Eleventy retrieves data from multiple sources. The most straightforward example is the front matter within page files or template files.

 

  ---
title: Post title
author: John Doe

---


<h1>{title}</h1>
<span>by {author}</span>

...

 

4-5 Retrieving Data from Headless CMS

Real projects require some form of CMS, but not all members of the content team are satisfied with editing md files and pushing them to git.

 

To retrieve data from the API, you need to create a JS file within the _data folder. This will make the data globally available.

 

If you want to retrieve data and use it within a specific range, you need to create a *.11tydata.js file in the template folder or directory folder.

 

You need to create a file in the directory folder.

 

  module.exports = async function () {
let response = await fetch(`https://api.domain/posts`)
let data = await response.json()

return data
}

 

4-6 Ecosystem

Eleventy has a starter list primarily created by the community. What's cool is that you can see the Lighthouse scores for each starting point, which are updated daily.

 

 

Eleventy has few ready-to-use plugins, but there are some plugins that add features like RSS, PWA, Tailwind, and Table of Contents.

 

4-7 How to Get Started?

To install Eleventy globally, run the command.

 

  npm install -g @11ty/eleventy
  

 

Next, we will create the folder and the index.md file.

 

  mkdir my-11ty-website && echo '# Hello world' > index.md
  

 

To start the Eleventy project locally, execute the following:

 

  eleventy --serve
  

 

Open http://localhost:8080 to display the website.

 

4-8 Conclusion

Eleventy may be the best choice to start your adventure in the world of Jamstack. It is flexible and does not require learning specific JS frameworks like React or Vue.

 

Features
  • Zero configuration, works with existing project structure
  • Supports 11 types of template languages
  • Client-side JavaScript is not required
  • Recommending progressive enhancement instead of a large JS payload
  • High-speed build. Generates 50k pages per minute
Use Case
  • Marketing Site with Progressive Enhancement
  • Creation of blogs and documents
  • E-commerce site with a lot of static content

5. Hugo

Last updated: October 26, 2020

 

Written in Go to achieve the fastest build time in the SSG market. Created by Steve Francia and Bjørn Erik Pedersen, it was first released on July 5, 2013. Currently, it is maintained by Mr. Bjørn. The popularity of Hugo lies in its speed and flexibility to easily create large websites.

 

Like Eleventy, Hugo also recommends progressive enhancement rather than full JS hydration. It has nothing to do with JavaScript frameworks.

 

5-1 Data Acquisition

Hugo only supports local flat files like markdown. If you want to edit content with a beautiful user interface, please use a Git-based CMS. Popular options include NetlifyCMS and Forestine.

 

To retrieve data from external APIs such as headless CMS, use the getJSON function.

 

  <div>
{{ $posts := getJSON "https://API.DOMAIN/posts" }} {{ range first 10 $posts }}
<article>
<h2>{{ .title }}</h2>
<div>{{ .content }}</div>
</article>
{{ end }}
</div>

 

5-2 File Structure

  ├── archetypes
│   └── default.md
├── config.toml
├── content
├── data
├── layouts
├── static
└── themes

 

Hugo has several high-level concepts like archetypes. Think of them as places where you can define fields for sections of your website, such as templates and content schemas.
If you want to learn more about a specific folder, please refer to the official documentation.

 

5-3 Ecosystem

Due to its high performance and simplicity, Hugo has gained many fans over the years. If any issues arise, you can get immediate answers on the official public forum.

 

 

Hugo collects a variety of themes. They are not official projects. Most of them are created by developers of Hugo around the world. They are provided under the MIT license, allowing for free use and modification. There are various categories available, including simple blogs, documentation, landing pages, and resumes.

 

5-4 How to Get Started?

The installation method varies depending on your OS, so please check the installation documentation. You can use Hugo even if you haven't installed Go.

 

Once you have installed Hugo, let's try running it.

 

  hugo new site my-hugo-website
  

 

You can now select a theme or create a new one.

 

  hugo new theme my-theme
  

 

To add content, execute this.

 

  hugo new posts/hello-world.md
  

 

To start the development server, execute as follows.

 

  hugo server -D
  

 

Your development environment is http://localhost:1313/

 

5-5 Conclusion

Hugo may feel a bit outdated for those who prefer modern JS frameworks like React, Vue, and Svelte. However, Hugo's age is also a strength. It has been proven in many big projects of well-known companies, so I am confident that it will not disappear overnight.

 

Features
  • Incredibly fast assembly time. Hugo is unbeatable when it comes to build time. Personally, I don't know of a faster Static Site Generator than Hugo, making it the best choice for large websites.
  • Cross-Platform. Hugo provides binaries for Windows, Linux, FreeBSD, NetBSD, macOS, and Android for x64, i386, and ARM architectures.
  • Client-side JavaScript is not required. Hugo is unrelated to any JS framework.
Use Case
  • Marketing sites and landing pages
  • Document

Related Blog Posts

Most Popular

For those who want to know more about manual production and instruction manual creation

Tokyo Headquarters: +81 35-321-3111

Reception hours: 9:30 AM to 5:00 PM JST

Contact Us / Request for Materials