Skip to content

Commit

Permalink
remove 3rd party codegen plugin and use native one
Browse files Browse the repository at this point in the history
  • Loading branch information
pettinarip committed May 24, 2022
1 parent 012d7c7 commit c529c9f
Show file tree
Hide file tree
Showing 10 changed files with 11,467 additions and 632 deletions.
18 changes: 3 additions & 15 deletions gatsby-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ const config: GatsbyConfig = {
})
.map((page) => ({ ...page, siteUrl: site.siteMetadata.siteUrl }))
},
serialize: ({ path, siteUrl }) => {
serialize: ({ path, siteUrl }: { path: string; siteUrl: string }) => {
const url = `${siteUrl}${path}`
const changefreq = path.includes(`/${defaultLanguage}/`)
? `weekly`
Expand Down Expand Up @@ -229,31 +229,19 @@ const config: GatsbyConfig = {
`gatsby-plugin-gatsby-cloud`,
// Creates `_redirects` & `_headers` build files for Netlify
`gatsby-plugin-netlify`,
// Enables codegen for graphql queries
{
resolve: `gatsby-plugin-graphql-codegen`,
options: {
codegen: true,
fileName: `./gatsby-graphql.ts`,
documentPaths: [
"./src/**/*.{ts,tsx}",
"./node_modules/gatsby-*/**/*.js",
"./gatsby-node.ts",
],
},
},
],
// https://www.gatsbyjs.com/docs/reference/release-notes/v2.28/#feature-flags-in-gatsby-configjs
flags: {
FAST_DEV: true, // DEV_SSR, QUERY_ON_DEMAND & LAZY_IMAGES
GRAPHQL_TYPEGEN: true, // ref. https://www.gatsbyjs.com/docs/reference/release-notes/v4.14/
},
}

// Avoid loading Matomo in preview deploys since NODE_ENV is `production` in
// there and it will send testing data as production otherwise
if (!isPreviewDeploy) {
config.plugins = [
...config.plugins,
...(config.plugins || []),
// Matomo analtyics
{
resolve: "gatsby-plugin-matomo",
Expand Down
8 changes: 8 additions & 0 deletions gatsby-graphql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,8 @@ export type DirectoryCtimeArgs = {
export type Site = Node & {
buildTime?: Maybe<Scalars['Date']>;
siteMetadata?: Maybe<SiteSiteMetadata>;
port?: Maybe<Scalars['Int']>;
host?: Maybe<Scalars['String']>;
flags?: Maybe<SiteFlags>;
polyfill?: Maybe<Scalars['Boolean']>;
pathPrefix?: Maybe<Scalars['String']>;
Expand Down Expand Up @@ -1723,6 +1725,8 @@ export type QueryAllDirectoryArgs = {
export type QuerySiteArgs = {
buildTime?: InputMaybe<DateQueryOperatorInput>;
siteMetadata?: InputMaybe<SiteSiteMetadataFilterInput>;
port?: InputMaybe<IntQueryOperatorInput>;
host?: InputMaybe<StringQueryOperatorInput>;
flags?: InputMaybe<SiteFlagsFilterInput>;
polyfill?: InputMaybe<BooleanQueryOperatorInput>;
pathPrefix?: InputMaybe<StringQueryOperatorInput>;
Expand Down Expand Up @@ -5849,6 +5853,8 @@ export type SiteFieldsEnum =
| 'siteMetadata___defaultLanguage'
| 'siteMetadata___supportedLanguages'
| 'siteMetadata___editContentUrl'
| 'port'
| 'host'
| 'flags___FAST_DEV'
| 'polyfill'
| 'pathPrefix'
Expand Down Expand Up @@ -5985,6 +5991,8 @@ export type SiteGroupConnectionGroupArgs = {
export type SiteFilterInput = {
buildTime?: InputMaybe<DateQueryOperatorInput>;
siteMetadata?: InputMaybe<SiteSiteMetadataFilterInput>;
port?: InputMaybe<IntQueryOperatorInput>;
host?: InputMaybe<StringQueryOperatorInput>;
flags?: InputMaybe<SiteFlagsFilterInput>;
polyfill?: InputMaybe<BooleanQueryOperatorInput>;
pathPrefix?: InputMaybe<StringQueryOperatorInput>;
Expand Down
43 changes: 26 additions & 17 deletions gatsby-node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { createFilePath } from "gatsby-source-filesystem"
import type { GatsbyNode } from "gatsby"

import type { Context } from "./src/types"
import type { AllMdxQuery } from "./gatsby-graphql"

import mergeTranslations from "./src/scripts/mergeTranslations"
import copyContributors from "./src/scripts/copyContributors"
Expand All @@ -30,7 +29,7 @@ const exec = util.promisify(child_process.exec)
* @param {string} filePath filepath for translated mdx file
* @returns boolean for if file is outdated or not
*/
const checkIsMdxOutdated = (filePath) => {
const checkIsMdxOutdated = (filePath: string): boolean => {
const dirname = path.resolve("./")
const splitPath = filePath.split(dirname)
const tempSplitPath = splitPath[1]
Expand All @@ -51,9 +50,11 @@ const checkIsMdxOutdated = (filePath) => {
let englishMatch = ""
let intlMatch = ""
try {
// @ts-expect-error
englishData.match(re).forEach((match) => {
englishMatch += match.replace(re, (_, p1, p2) => p1 + p2)
})
// @ts-expect-error
translatedData.match(re).forEach((match) => {
intlMatch += match.replace(re, (_, p1, p2) => p1 + p2)
})
Expand All @@ -74,7 +75,10 @@ const checkIsMdxOutdated = (filePath) => {
* @param {*} lang language abbreviation for language path
* @returns {{isOutdated: boolean, isContentEnglish: boolean}}
*/
const checkIsPageOutdated = async (urlPath, lang) => {
const checkIsPageOutdated = async (
urlPath: string,
lang: Lang
): Promise<{ isOutdated: boolean; isContentEnglish: boolean }> => {
// Files that need index appended on the end. Ex page-index.json, page-developers-index.json, page-upgrades-index.json
const indexFilePaths = ["", "developers", "upgrades"]
const filePath = urlPath.split("/").filter((text) => text !== "")
Expand Down Expand Up @@ -137,11 +141,9 @@ const checkIsPageOutdated = async (urlPath, lang) => {

// Loops through all the files dictated by Gatsby (building pages folder), as well as
// folders flagged through the gatsby-source-filesystem plugin in gatsby-config
export const onCreateNode: GatsbyNode["onCreateNode"] = async ({
node,
getNode,
actions,
}) => {
export const onCreateNode: GatsbyNode<{
fileAbsolutePath: string
}>["onCreateNode"] = async ({ node, getNode, actions }) => {
const { createNodeField } = actions

// Edit markdown nodes
Expand Down Expand Up @@ -200,7 +202,7 @@ export const createPages: GatsbyNode<any, Context>["createPages"] = async ({
})
})

const result = await graphql<AllMdxQuery>(`
const { data, errors } = await graphql<Queries.AllMdxQuery>(`
query AllMdx {
allMdx {
edges {
Expand All @@ -220,16 +222,20 @@ export const createPages: GatsbyNode<any, Context>["createPages"] = async ({
}
`)

if (result.errors) {
if (errors) {
reporter.panicOnBuild('🚨 ERROR: Loading "createPages" query')
}

// For all markdown nodes, create a page
result.data.allMdx.edges.filter(({ node }) => {
const slug = node.fields.slug
data?.allMdx.edges.filter(({ node }) => {
const slug = node.fields?.slug

if (!slug) {
throw new Error(`Missing 'slug' node property.`)
}

// Set template of markdown files
const nodeTemplate = node.frontmatter.template
const nodeTemplate = node.frontmatter?.template
let template = nodeTemplate ? nodeTemplate : `static`
if (slug.includes(`/tutorials/`)) {
template = `tutorial`
Expand All @@ -243,11 +249,14 @@ export const createPages: GatsbyNode<any, Context>["createPages"] = async ({
slug.includes(`/terms-of-use/`) ||
slug.includes(`/contributing/`) ||
slug.includes(`/style-guide/`)
const language = node.frontmatter.lang as Lang
const language = node.frontmatter?.lang as Lang
if (!language) {
throw `Missing 'lang' frontmatter property. All markdown pages must have a lang property. Page slug: ${slug}`
}
const relativePath = node.fields.relativePath
if (!relativePath) {
throw new Error(`Missing 'relativePath' node property.`)
}

// If markdown file is English, check for corresponding file in each language.
// e.g. English file: "src/content/community/index.md"
Expand Down Expand Up @@ -294,7 +303,7 @@ export const createPages: GatsbyNode<any, Context>["createPages"] = async ({
component: path.resolve(`src/templates/${template}.js`),
context: {
slug,
isOutdated: node.fields.isOutdated,
isOutdated: !!node.fields.isOutdated,
relativePath: relativePath,
// Create `intl` object so `gatsby-plugin-intl` will skip
// generating language variations for this page
Expand Down Expand Up @@ -370,7 +379,7 @@ export const onCreatePage: GatsbyNode<any, Context>["onCreatePage"] = async ({
if (isTranslated && hasNoContext) {
const { isOutdated, isContentEnglish } = await checkIsPageOutdated(
page.context.intl.originalPath,
page.context.language
page.context.language!
)
deletePage(page)
createPage<Context>({
Expand Down Expand Up @@ -449,7 +458,7 @@ export const onPostBuild: GatsbyNode["onPostBuild"] = async (
) => {
const { reporter } = gatsbyNodeHelpers

const reportOut = (report) => {
const reportOut = (report: { stderr: string; stdout: string }) => {
const { stderr, stdout } = report
if (stderr) reporter.error(stderr)
if (stdout) reporter.info(stdout)
Expand Down
1 change: 1 addition & 0 deletions graphql.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
module.exports = require("./.cache/typegen/graphql.config.json")
4 changes: 4 additions & 0 deletions overrides.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// temporary override until we figure out how to solve the `getImage` type
// errors.
// TODO: create issue in Gatsby repo
declare module "gatsby-plugin-image"
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,8 @@
"dotenv": "^8.2.0",
"ethereum-blockies-base64": "^1.0.2",
"framer-motion": "^4.1.3",
"gatsby": "^4.10.0",
"gatsby": "^4.14.0",
"gatsby-plugin-gatsby-cloud": "^4.3.0",
"gatsby-plugin-graphql-codegen": "^3.1.1",
"gatsby-plugin-image": "^2.0.0",
"gatsby-plugin-intl": "^0.3.3",
"gatsby-plugin-manifest": "^4.10.1",
Expand Down
Loading

0 comments on commit c529c9f

Please sign in to comment.