DEV Community

Tomoyuki Kashiro
Tomoyuki Kashiro

Posted on • Originally published at blog.tomoyukikashiro.me on

AMP to PWA for Gatsby

This post was originally published at AMP to PWA for Gatsby.

What’s AMP to PWA

It’s also known as Preload your Progressive Web App from your AMP pages.

A good strategy is to make the entry point into your site an AMP page, then warm up the PWA behind the scenes and switch to it for the onward journey:

For more detail plz check AMP official article.

Goal of this article

I’ll explain how to implement it for blog using Gatsby.

Table of Contents

  • Prepare Blog
  • Change article path
  • Prepare AMP generation
  • Add Service Worker installer in AMP for Non-AMP page
  • Add AMP validation in Test (optional)
  • Build

Prepare Blog

$ npm install -g gatsby-cli
$ gatsby new my-blog-starter https://github.com/gatsbyjs/gatsby-starter-blog
$ cd my-blog-starter/

Change article path

By default, Blog articles locate in root (e.g. /hello-world, /hi-folks). We want to publish Non-AMP article and AMP article so let’s separate directories like this.

  • Non-AMP : /posts
  • AMP : /amp/posts

At first, Change Non-AMP publish path.

- Change path in meta tags like canonical at src/components/seo.js

Change link path at contents

Prepare AMP generation

To generate AMP page from HTML I use gatsby-plugin-html2amp. This plugin allow you to generate AMP page using regular HTML so all you have to do is to install it and add configuration !

$ npm install --save gatsby-plugin-html2amp

and add configuration.

Add Service Worker installer in AMP for Non-AMP page

This is the most important key point of this strategy. Once user access AMP page this site starts installing service worker to cache resources for Non-AMP page.

After installation and user clicks link which links to Non-AMP page, the page load instantly because most resources are cached.amp-install-serviceworker is AMP component for that.

Fortunately, gatsby-plugin-html2amp already has integration for it so what you need is to add configuration only !!

Add AMP validation in Test

This is optional. Let’s add test to check validation for AMP page.

$ npm install --save-dev amphtml-validator
  • Add test command at pacakge.json
  • Run test by following command
$ npm test

Build both

Note that gatsby-plugin-html2amp generate AMP in build process only so when you run npm run develop you can not browse AMP page. When you check Non-AMP and AMP page run following command.

$ npm run build
$ npm run serve

Sample

I made Sample project here.

Top comments (0)