DevTips -- gatsby

moon indicating dark mode
sun indicating light mode
Gatsby.js is a static PWA (Progressive Web App) generator. You get code and data splitting out-of-the-box. Gatsby loads only the critical HTML, CSS, data, and JavaScript so your site loads as fast as possible. Once loaded, Gatsby prefetches resources for other pages so clicking around the site feels incredibly fast.

Change Page URL

Using onCreatePage in @gatsbyjs allows you to change various aspects of pages created by plugins you don't control, such as the URL.

exports.onCreatePage = ({ page, actions }) => {
const { createPage, deletePage } = actions;
const oldPage = Object.assign({}, page);
if (oldPage.path === "/posts") {
page.path = "/blog-posts";
deletePage(oldPage);
createPage(page);
}
};

Change Page Context

Using onCreatePage in @gatsbyjs allows you to change various aspects of pages created by plugins you don't control, such as the page context which is passed to the page queries in templates.

exports.onCreatePage = ({ page, actions }) => {
const { createPage, deletePage } = actions;
const oldPage = Object.assign({}, page);
if (oldPage.path === "/posts") {
page.path = "/blog-posts";
deletePage(oldPage);
createPage(page);
}
};

fix nested types

In @gatsbyjs, you can fix nested types (like Frontmatter) by specifying the field on the root type

exports.createSchemaCustomization = ({ actions }) => {
createTypes(`
type MarkdownRemark implements Node {
frontmatter: Frontmatter
}
type Frontmatter {
tags: [String!]!
}
`);
};

createFieldExtension

Field Extensions in @gatsbyjs allow you to extend resolvers for specific fields with additional functionality via GraphQL directives

exports.createSchemaCustomization = ({ actions }) => {
const { createTypes, createFieldExtension } = actions;
createFieldExtension({
name: "shout",
extend: () => ({
resolve(source, args, context, info) {
return String(source[info.fieldName]).toUpperCase();
}
})
});
const typeDefs = `
type BlogPost {
title: String! @shout
}
`;
createTypes(typeDefs);
};

createSchemaCustomization

In @gatsbyjs, there is a lifecycle dedicated to the task of modifying the types available and creating new types in the GraphQL API

exports.createSchemaCustomization = ({ actions }) => {
const { createTypes } = actions;
const typeDefs = `
type MarkdownRemark implements Node @dontInfer {
frontmatter: Frontmatter
}
type Frontmatter {
title: String!
tagline: String
date: Date @dateformat
image: File @fileByRelativePath
}
`;
createTypes(typeDefs);
};