GatsbyJS - Cookbook

Updated: 2019-01-03

Multiple Source Folders

gatsby-source-filesystem can load multiple folders. In gatsby-config.js:

{
  resolve: `gatsby-source-filesystem`,
  options: {
    path: `${__dirname}/src/pages`,
    name: "pages"
  }
},
{
  resolve: `gatsby-source-filesystem`,
  options: {
    path: `${__dirname}/src/images`,
    name: "images"
  }
},

Then you can query images like src/images/logo.png like this:

query {
  logo: file(relativePath: { eq: "logo.png" }) {
    childImageSharp {
      fixed(width: 180, height: 40) {
        ...GatsbyImageSharpFixed_noBase64
      }
    }
  }
}

Ignore Some Folders/Files

.gitignore can exclude files from being checked in; how to exclude files from Gastby site generation? Use ignore in gatsby-config.js:

    {
      resolve: `gatsby-source-filesystem`,
      options: {
        path: `${__dirname}/src/pages`,
        name: "pages",
        ignore: [`**/_draft`]
      }
    },

Then add these 2 plugins to gatsby-configs.js:

{
  resolve: `gatsby-plugin-manifest`,
  options: {
    name: `...`,
    short_name: `...`,
    start_url: `/`,
    background_color: `#ddd`,
    theme_color: `#000000`,
    display: `minimal-ui`,
    icon: `src/images/logo.png`
  }
},
`gatsby-plugin-offline`

Updated Timestamp

In gatsby-node.js, add modifiedTime, which can be derived from parent node(File), to MarkdownRemark node:

exports.onCreateNode = ({ node, getNode, actions }) => {
  const { createNodeField } = actions;
  if (node.internal.type === `MarkdownRemark`) {
    // ...
    const parent = getNode(node.parent);
    createNodeField({
      node,
      name: `modifiedTime`,
      value: parent.modifiedTime.slice(0, 10)
    });
  }
};

Then query it like this:

query($slug: String!) {
  markdownRemark(fields: { slug: { eq: $slug } }) {
    ...
    fields {
      modifiedTime
    }
  }
}

Progressive Web App (PWA)

Install the 2 key plugins:

$ npm i gatsby-plugin-manifest gatsby-plugin-offline

React Helmet

Also anything you render in the html.js component will not be made “live” in the client like other components. If you want to dynamically update your <head> we recommend using React Helmet

Source plugins

gatsby-source-xxx

e.g. gatsby-source-filesystem

New nodes are added to Gatsby by “source” plugins. A common one that many Gatsby sites use is the Filesystem source plugin which turns files on disk into File nodes. Other source plugins pull data from external APIs such as the Drupal andHacker News

Transformer plugins

gatsby-transformer-xxx

e.g. gatsby-transformer-remark

Transformer plugins can also create nodes by transforming source nodes into new types of nodes. It is very common when building Gatsby sites to install both source plugin(s) and transformer plugins.

functional plugins

gatsby-plugin-xxx

e.g. gatsby-plugin-sitemap, gatsby-plugin-google-analytics