DEV Community

Tomoyuki Kashiro
Tomoyuki Kashiro

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

AMP ⚡ using Gatsby

This post was originally published at AMP ⚡ using Gatsby.

I created gatsby plugin (called gatsby-plugin-html2amp) for generating AMP (Accelerated Mobile Pages). I try to explain how to use it.

It’s easy to use 😁

Prepare Gatsby blog

$ npm install --global gatsby-cli
$ gatsby new gatsby-blog https://github.com/gatsbyjs/gatsby-starter-blog
Enter fullscreen mode Exit fullscreen mode

then check the blog

$ cd gatsby-blog
$ npm start

# Access http://localhost:8000
Enter fullscreen mode Exit fullscreen mode

Make it AMP !

Add plugin

$ npm install --save gatsby-plugin-html2amp
Enter fullscreen mode Exit fullscreen mode

Set plugin configuration to gatsby-config.js at bottom of file.

{
  resolve: 'gatsby-plugin-html2amp',
  options: {
    files: ['**/*.html'],
    dist: 'public/amp'
  }
}
Enter fullscreen mode Exit fullscreen mode

Modify blog post template

To make your post page valid as AMP add canonical in <head>

src/templates/blog-post.js

export const pageQuery = graphql`
  query BlogPostBySlug($slug: String!) {
    site {
      siteMetadata {
        title
        author
      }
    }
    markdownRemark(fields: { slug: { eq: $slug } }) {
      id
      excerpt
      html
      fields { // ⚡ Add this fields.slug into Graphql
        slug
      }
      frontmatter {
        title
        date(formatString: "MMMM DD, YYYY")
      }
    }
  }
`
Enter fullscreen mode Exit fullscreen mode

then add canonical

src/templates/blog-post.js

<Helmet
  htmlAttributes={{ lang: 'en' }}
  meta={[{ name: 'description', content: siteDescription }]}
  title={`${post.frontmatter.title} | ${siteTitle}`}>
  <link rel="canonical" href={`${post.fields.slug}`} /> // ⚡ Add canonical
</Helmet>
Enter fullscreen mode Exit fullscreen mode

Generate

$ npm run build
Enter fullscreen mode Exit fullscreen mode

Now you can see AMP source at public/amp

Top comments (1)

Collapse
 
turq84 profile image
Kayla Gordon

Thank you so much for your hard work! I have a question for you.

I'm using Gatsby JS for my company website, but I only want to create an AMP template for some of the pages. Is there any way to do this with your html2amp plugins? I know you can create custom templates in html2amp, but is something like that possible with Gatsby JS? Please forgive me if my question is silly. I'm still learning AMP.