From 031a08f92224ff4027c12448bb2011d504651827 Mon Sep 17 00:00:00 2001 From: Lennart Date: Fri, 9 Dec 2022 03:26:26 +0100 Subject: [PATCH 01/92] fix(gatsby): Improve readability of page data / long running query warnings (#37220) * show better page data information * clean up longrunning queries Alternative to https://github.com/gatsbyjs/gatsby/pull/36876 Co-authored-by: Tyler Barnes Co-authored-by: Daniel Lew Co-authored-by: Tyler Barnes Co-authored-by: Daniel Lew --- packages/gatsby/src/commands/build-html.ts | 29 ++--- packages/gatsby/src/query/query-runner.ts | 13 +-- .../gatsby/src/utils/__tests__/page-data.ts | 110 ++++++++++++++++++ packages/gatsby/src/utils/page-data.ts | 42 +++++++ .../src/utils/worker/child/render-html.ts | 26 ++--- 5 files changed, 172 insertions(+), 48 deletions(-) diff --git a/packages/gatsby/src/commands/build-html.ts b/packages/gatsby/src/commands/build-html.ts index 14110b0b599f5..efc1cc3f5bb1b 100644 --- a/packages/gatsby/src/commands/build-html.ts +++ b/packages/gatsby/src/commands/build-html.ts @@ -2,7 +2,7 @@ import Bluebird from "bluebird" import fs from "fs-extra" import reporter from "gatsby-cli/lib/reporter" import { createErrorFromString } from "gatsby-cli/lib/reporter/errors" -import { chunk, truncate } from "lodash" +import { chunk } from "lodash" import { build, watch } from "../utils/webpack/bundle" import * as path from "path" import fastq from "fastq" @@ -18,7 +18,6 @@ import { Span } from "opentracing" import { IProgram, Stage } from "./types" import { ROUTES_DIRECTORY } from "../constants" import { PackageJson } from "../.." -import { IPageDataWithQueryResult } from "../utils/page-data" import { getPublicPath } from "../utils/get-public-path" import type { GatsbyWorkerPool } from "../utils/worker/pool" @@ -26,6 +25,7 @@ import { stitchSliceForAPage } from "../utils/slices/stitching" import type { ISlicePropsEntry } from "../utils/worker/child/render-html" import { getPageMode } from "../utils/page-mode" import { extractUndefinedGlobal } from "../utils/extract-undefined-global" +import { modifyPageDataForErrorMessage } from "../utils/page-data" type IActivity = any // TODO @@ -532,20 +532,6 @@ class BuildHTMLError extends Error { } } -const truncateObjStrings = (obj): IPageDataWithQueryResult => { - // Recursively truncate strings nested in object - // These objs can be quite large, but we want to preserve each field - for (const key in obj) { - if (typeof obj[key] === `object`) { - truncateObjStrings(obj[key]) - } else if (typeof obj[key] === `string`) { - obj[key] = truncate(obj[key], { length: 250 }) - } - } - - return obj -} - export const doBuildPages = async ( rendererPath: string, pagePaths: Array, @@ -563,22 +549,23 @@ export const doBuildPages = async ( if (error?.context?.path) { const pageData = await getPageData(error.context.path) - const truncatedPageData = truncateObjStrings(pageData) + const modifiedPageDataForErrorMessage = + modifyPageDataForErrorMessage(pageData) - const pageDataMessage = `Page data from page-data.json for the failed page "${ + const errorMessage = `Truncated page data information for the failed page "${ error.context.path - }": ${JSON.stringify(truncatedPageData, null, 2)}` + }": ${JSON.stringify(modifiedPageDataForErrorMessage, null, 2)}` // This is our only error during preview so customize it a bit + add the // pretty build error. if (isPreview) { reporter.error({ id: `95314`, - context: { pageData: pageDataMessage }, + context: { errorMessage }, error: buildError, }) } else { - reporter.error(pageDataMessage) + reporter.error(errorMessage) } } diff --git a/packages/gatsby/src/query/query-runner.ts b/packages/gatsby/src/query/query-runner.ts index c1caabd13e1c1..f652947f5f930 100644 --- a/packages/gatsby/src/query/query-runner.ts +++ b/packages/gatsby/src/query/query-runner.ts @@ -37,19 +37,14 @@ export interface IQueryJob { pluginCreatorId?: string } -function reportLongRunningQueryJob(queryJob): void { +function reportLongRunningQueryJob(queryJob: IQueryJob): void { const messageParts = [ - `This query took more than 15s to run β€” which is unusually long and might indicate you're querying too much or have some unoptimized code:`, + `This query took more than 15s to run β€” which might indicate you're querying too much or have some unoptimized code:`, `File path: ${queryJob.componentPath}`, ] - if (queryJob.isPage) { - const { path, context } = queryJob.context - messageParts.push(`URL path: ${path}`) - - if (!_.isEmpty(context)) { - messageParts.push(`Context: ${JSON.stringify(context, null, 4)}`) - } + if (queryJob.queryType === `page`) { + messageParts.push(`URL path: ${queryJob.context.path}`) } report.warn(messageParts.join(`\n`)) diff --git a/packages/gatsby/src/utils/__tests__/page-data.ts b/packages/gatsby/src/utils/__tests__/page-data.ts index 1a570c9d41e3a..c999faae3afe2 100644 --- a/packages/gatsby/src/utils/__tests__/page-data.ts +++ b/packages/gatsby/src/utils/__tests__/page-data.ts @@ -4,6 +4,8 @@ import { savePageQueryResult, readPageQueryResult, waitUntilPageQueryResultsAreStored, + modifyPageDataForErrorMessage, + IPageDataWithQueryResult, } from "../page-data" describe(`savePageQueryResults / readPageQueryResults`, () => { @@ -24,3 +26,111 @@ describe(`savePageQueryResults / readPageQueryResults`, () => { expect(JSON.parse(result)).toEqual(inputResult) }) }) + +describe(`modifyPageDataForErrorMessage`, () => { + it(`handles optional data gracefully`, () => { + const input: IPageDataWithQueryResult = { + path: `/foo/`, + componentChunkName: `component`, + matchPath: `/`, + slicesMap: {}, + staticQueryHashes: [], + result: {}, + } + expect(modifyPageDataForErrorMessage(input)).toMatchInlineSnapshot(` + Object { + "errors": Object {}, + "matchPath": "/", + "path": "/foo/", + "slicesMap": Object {}, + } + `) + }) + it(`outputs expected result shape`, () => { + const input: IPageDataWithQueryResult = { + path: `/foo/`, + componentChunkName: `component`, + matchPath: `/`, + slicesMap: { + foo: `bar`, + }, + getServerDataError: [ + { + level: `ERROR`, + text: `error`, + stack: [{ fileName: `a` }], + type: `UNKNOWN`, + }, + ], + staticQueryHashes: [`123`], + result: { + data: undefined, + // @ts-ignore - Can ignore for this test + errors: [`error`], + extensions: { + foo: `bar`, + }, + pageContext: { + foo: `bar`, + }, + serverData: { + foo: `bar`, + }, + }, + } + expect(modifyPageDataForErrorMessage(input)).toMatchInlineSnapshot(` + Object { + "errors": Object { + "getServerData": Array [ + Object { + "level": "ERROR", + "stack": Array [ + Object { + "fileName": "a", + }, + ], + "text": "error", + "type": "UNKNOWN", + }, + ], + "graphql": Array [ + "error", + ], + }, + "matchPath": "/", + "pageContext": Object { + "foo": "bar", + }, + "path": "/foo/", + "slicesMap": Object { + "foo": "bar", + }, + } + `) + }) + it(`doesn't print out the GraphQL result and serverData result`, () => { + const input: IPageDataWithQueryResult = { + path: `/foo/`, + componentChunkName: `component`, + matchPath: `/`, + slicesMap: {}, + staticQueryHashes: [], + result: { + data: { + foo: `bar`, + }, + serverData: { + foo: `bar`, + }, + }, + } + expect(modifyPageDataForErrorMessage(input)).toMatchInlineSnapshot(` + Object { + "errors": Object {}, + "matchPath": "/", + "path": "/foo/", + "slicesMap": Object {}, + } + `) + }) +}) diff --git a/packages/gatsby/src/utils/page-data.ts b/packages/gatsby/src/utils/page-data.ts index 7f90a52fbee87..c3b055d2a0e81 100644 --- a/packages/gatsby/src/utils/page-data.ts +++ b/packages/gatsby/src/utils/page-data.ts @@ -452,3 +452,45 @@ export async function handleStalePageData(parentSpan: Span): Promise { activity.end() } + +interface IModifyPageDataForErrorMessage { + errors: { + graphql?: IPageDataWithQueryResult["result"]["errors"] + getServerData?: IPageDataWithQueryResult["getServerDataError"] + } + graphqlExtensions?: IPageDataWithQueryResult["result"]["extensions"] + pageContext?: IPageDataWithQueryResult["result"]["pageContext"] + path: IPageDataWithQueryResult["path"] + matchPath: IPageDataWithQueryResult["matchPath"] + slicesMap: IPageDataWithQueryResult["slicesMap"] +} + +export function modifyPageDataForErrorMessage( + input: IPageDataWithQueryResult +): IModifyPageDataForErrorMessage { + const optionalData = { + ...(input.result?.pageContext + ? { pageContext: input.result.pageContext } + : {}), + ...(input.result?.pageContext + ? { pageContext: input.result.pageContext } + : {}), + } + + const optionalErrors = { + ...(input.result?.errors ? { graphql: input.result.errors } : {}), + ...(input.getServerDataError + ? { getServerData: input.getServerDataError } + : {}), + } + + return { + errors: { + ...optionalErrors, + }, + path: input.path, + matchPath: input.matchPath, + slicesMap: input.slicesMap, + ...optionalData, + } +} diff --git a/packages/gatsby/src/utils/worker/child/render-html.ts b/packages/gatsby/src/utils/worker/child/render-html.ts index d6176ad85f5fa..8de92cb7873d8 100644 --- a/packages/gatsby/src/utils/worker/child/render-html.ts +++ b/packages/gatsby/src/utils/worker/child/render-html.ts @@ -5,7 +5,6 @@ import Bluebird from "bluebird" import * as path from "path" import { generateHtmlPath } from "gatsby-core-utils/page-html" import { generatePageDataPath } from "gatsby-core-utils/page-data" -import { truncate } from "lodash" import { readWebpackStats, @@ -14,6 +13,7 @@ import { } from "../../client-assets-for-template" import { IPageDataWithQueryResult, + modifyPageDataForErrorMessage, readPageData, readSliceData, } from "../../page-data" @@ -135,20 +135,6 @@ async function getResourcesForTemplate( return resources } -const truncateObjStrings = (obj): IPageDataWithQueryResult => { - // Recursively truncate strings nested in object - // These objs can be quite large, but we want to preserve each field - for (const key in obj) { - if (typeof obj[key] === `object` && obj[key] !== null) { - truncateObjStrings(obj[key]) - } else if (typeof obj[key] === `string`) { - obj[key] = truncate(obj[key], { length: 250 }) - } - } - - return obj -} - interface IPreviewErrorProps { pagePath: string publicDir: string @@ -161,7 +147,7 @@ const generatePreviewErrorPage = async ({ error, }: IPreviewErrorProps): Promise => { const pageData = await readPageData(publicDir, pagePath) - const truncatedPageData = truncateObjStrings(pageData) + const pageDataForErrorMessage = modifyPageDataForErrorMessage(pageData) const html = ` @@ -359,8 +345,12 @@ const generatePreviewErrorPage = async ({

Below you'll find additional data that might help you debug the error.

Page Data -

The page data contains some metadata about the affected page but also the GraphQL data if you have queries in your page. If e.g. data from the GraphQL query is undefined, check if it's available here.

-
${JSON.stringify(truncatedPageData, null, 2)}
+

The page data contains some metadata about the affected page. If data from the GraphQL is undefined, try running the query in the GraphiQL IDE.

+
${JSON.stringify(
+          pageDataForErrorMessage,
+          null,
+          2
+        )}
From ba4b0954e9d41f2ebc186a1b472a45e49d3b0785 Mon Sep 17 00:00:00 2001 From: GatsbyJS Bot Date: Fri, 9 Dec 2022 00:54:32 -0700 Subject: [PATCH 02/92] chore(changelogs): update changelogs (#37226) --- packages/gatsby-source-wordpress/CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/gatsby-source-wordpress/CHANGELOG.md b/packages/gatsby-source-wordpress/CHANGELOG.md index e56b54561639a..a356a5e9c5f68 100644 --- a/packages/gatsby-source-wordpress/CHANGELOG.md +++ b/packages/gatsby-source-wordpress/CHANGELOG.md @@ -3,6 +3,12 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +### [7.2.3](https://github.com/gatsbyjs/gatsby/commits/gatsby-source-wordpress@7.2.3/packages/gatsby-source-wordpress) (2022-12-08) + +#### Bug Fixes + +- Add back nodeType field that was removed in last version [#37212](https://github.com/gatsbyjs/gatsby/issues/37212) [#37219](https://github.com/gatsbyjs/gatsby/issues/37219) ([815791a](https://github.com/gatsbyjs/gatsby/commit/815791a4fd4cf336acc898cd26b2e8768e5f24bc)) + ### [7.2.2](https://github.com/gatsbyjs/gatsby/commits/gatsby-source-wordpress@7.2.2/packages/gatsby-source-wordpress) (2022-12-07) #### Chores From f0883695778ad5b9e1a436255deb5aa976616048 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 9 Dec 2022 08:54:49 +0100 Subject: [PATCH 03/92] fix(deps): update starters and examples gatsby packages to ^7.2.3 (#37224) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- .../package-lock.json | 14 +++++++------- .../gatsby-starter-wordpress-blog/package.json | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/starters/gatsby-starter-wordpress-blog/package-lock.json b/starters/gatsby-starter-wordpress-blog/package-lock.json index 206230676dc03..f489156a77785 100644 --- a/starters/gatsby-starter-wordpress-blog/package-lock.json +++ b/starters/gatsby-starter-wordpress-blog/package-lock.json @@ -16,7 +16,7 @@ "gatsby-plugin-image": "^3.2.0", "gatsby-plugin-manifest": "^5.2.0", "gatsby-plugin-sharp": "^5.2.0", - "gatsby-source-wordpress": "^7.2.1", + "gatsby-source-wordpress": "^7.2.3", "gatsby-transformer-sharp": "^5.2.0", "html-react-parser": "^3.0.4", "lodash": "^4.17.21", @@ -10188,9 +10188,9 @@ } }, "node_modules/gatsby-source-wordpress": { - "version": "7.2.1", - "resolved": "https://registry.npmjs.org/gatsby-source-wordpress/-/gatsby-source-wordpress-7.2.1.tgz", - "integrity": "sha512-R9v0x6BmbP/bYBZo3BR+7qz8YWBxkO1mucxJCz/YMubPDOnYxFfHvGuSC8lDDEDqKAmo27Nze3+B4nE7YR5xsQ==", + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/gatsby-source-wordpress/-/gatsby-source-wordpress-7.2.3.tgz", + "integrity": "sha512-mnWKRfHb8M+YHYmhDEnFnBgWyQJWJGm+oXph4AgRwS1TJQiSSYXaqNbOrrrymCrCMlomLfpnpfbCgEy6sxI2MA==", "dependencies": { "@babel/runtime": "^7.15.4", "@rematch/core": "^1.4.0", @@ -25260,9 +25260,9 @@ } }, "gatsby-source-wordpress": { - "version": "7.2.1", - "resolved": "https://registry.npmjs.org/gatsby-source-wordpress/-/gatsby-source-wordpress-7.2.1.tgz", - "integrity": "sha512-R9v0x6BmbP/bYBZo3BR+7qz8YWBxkO1mucxJCz/YMubPDOnYxFfHvGuSC8lDDEDqKAmo27Nze3+B4nE7YR5xsQ==", + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/gatsby-source-wordpress/-/gatsby-source-wordpress-7.2.3.tgz", + "integrity": "sha512-mnWKRfHb8M+YHYmhDEnFnBgWyQJWJGm+oXph4AgRwS1TJQiSSYXaqNbOrrrymCrCMlomLfpnpfbCgEy6sxI2MA==", "requires": { "@babel/runtime": "^7.15.4", "@rematch/core": "^1.4.0", diff --git a/starters/gatsby-starter-wordpress-blog/package.json b/starters/gatsby-starter-wordpress-blog/package.json index 8f8daa5d1e0b2..d8352518bee13 100644 --- a/starters/gatsby-starter-wordpress-blog/package.json +++ b/starters/gatsby-starter-wordpress-blog/package.json @@ -15,7 +15,7 @@ "gatsby-plugin-image": "^3.2.0", "gatsby-plugin-manifest": "^5.2.0", "gatsby-plugin-sharp": "^5.2.0", - "gatsby-source-wordpress": "^7.2.1", + "gatsby-source-wordpress": "^7.2.3", "gatsby-transformer-sharp": "^5.2.0", "html-react-parser": "^3.0.4", "lodash": "^4.17.21", From cb92dfe0d6bb71d9797067a6c23dfc4a813ef529 Mon Sep 17 00:00:00 2001 From: Florian Kissling <21834+fk@users.noreply.github.com> Date: Fri, 9 Dec 2022 08:59:21 +0100 Subject: [PATCH 04/92] chore(docs): Switch to `Announcement` shortcode (#36628) --- docs/docs/conceptual/gatsby-for-ecommerce.md | 4 +-- docs/docs/conceptual/rendering-options.md | 6 ++-- .../creating-a-source-plugin.md | 4 +-- .../migrating-source-plugin-from-v3-to-v4.md | 4 +-- docs/docs/tutorial/part-0/index.mdx | 20 +++++------ docs/docs/tutorial/part-1/index.mdx | 26 +++++++------- docs/docs/tutorial/part-2/index.mdx | 36 +++++++++---------- docs/docs/tutorial/part-3/index.mdx | 18 +++++----- docs/docs/tutorial/part-4/index.mdx | 34 +++++++++--------- docs/docs/tutorial/part-5/index.mdx | 26 +++++++------- docs/docs/tutorial/part-6/index.mdx | 20 +++++------ docs/docs/tutorial/part-7/index.mdx | 28 +++++++-------- 12 files changed, 109 insertions(+), 117 deletions(-) diff --git a/docs/docs/conceptual/gatsby-for-ecommerce.md b/docs/docs/conceptual/gatsby-for-ecommerce.md index b9c0dfe2f63d5..269351001f7ea 100644 --- a/docs/docs/conceptual/gatsby-for-ecommerce.md +++ b/docs/docs/conceptual/gatsby-for-ecommerce.md @@ -2,8 +2,6 @@ title: Using Gatsby For E-commerce --- -import { Announcement } from "gatsby-interface" - Businesses selling products online typically need a variety of software to support their experience. At a minimum, their website needs product pages, product catalog navigation, a shopping cart, and checkout. Most have additional functionality like customer account creation, promotions, discounts, and loyalty, customer reviews, tax calculation, user tracking via analytics, and content personalization. @@ -42,7 +40,7 @@ E-commerce tends to have a number of specific requirements. When building a Gats ## Additional resources: - + Check out our [e-commerce demo](https://shopify-demo.gatsbyjs.com/) built with our Shopify Starter, a proof of concept showcasing 10,000 products and 30,000 SKUs (variants). Clone our Shopify Starter, host it on Gatsby and connect it to your own Shopify data to develop your own proof of concept in as little as an hour. diff --git a/docs/docs/conceptual/rendering-options.md b/docs/docs/conceptual/rendering-options.md index 78327860667f3..971cf2f9466dc 100644 --- a/docs/docs/conceptual/rendering-options.md +++ b/docs/docs/conceptual/rendering-options.md @@ -2,8 +2,6 @@ title: Rendering Options --- -import { Announcement } from "gatsby-interface" - Gatsby is historically known as a static site generator enhanced with [React Hydration][1]. But starting with Gatsby 4, you can choose alternative rendering options in addition to static site generation (SSG) β€” on a per-page basis. This type of granular control allows you to optimize for performance and productivity without sacrificing one for the other. @@ -14,7 +12,7 @@ A rendering option defines the stage at which your page's user-facing HTML is ge (SSG or pre-rendering), during HTTP request (server-side rendering) or locally in the browser with Javascript (client-side rendering). - + For an in-depth explanation of each of those approaches and their trade-offs we highly recommend the ["Rendering on the Web"][3] article from the Chrome team. @@ -35,7 +33,7 @@ How does SSG work? This mode provides the most pleasant user experience, the highest level of security, and run-time scalability for your site. - + **Note:** SSG doesn't mean your site is not dynamic. You can still use JavaScript to communicate with any APIs, add private sections of your site for authorized users via [client-side rendering][4] and diff --git a/docs/docs/how-to/plugins-and-themes/creating-a-source-plugin.md b/docs/docs/how-to/plugins-and-themes/creating-a-source-plugin.md index 3a6bf37c2c602..4b2554c3a2ce5 100644 --- a/docs/docs/how-to/plugins-and-themes/creating-a-source-plugin.md +++ b/docs/docs/how-to/plugins-and-themes/creating-a-source-plugin.md @@ -3,8 +3,6 @@ title: "Creating a Source Plugin" tableOfContentsDepth: 2 --- -import { Announcement } from "gatsby-interface" - Source plugins are reusable integrations with content and data backends. There are already [100s of ready-to-use source plugins for popular content APIs](/plugins/?=gatsby-source) like Contentful, Drupal, and WordPress. This tutorial teaches you how to build your own integration. In this tutorial, you'll create your own source plugin that will gather data from an API. The plugin will source data, optimize remote images, and create foreign key relationships between data sourced by your plugin. @@ -556,7 +554,7 @@ if (fileNode) { By using [`createNodeField`](/docs/reference/config-files/actions/#createNodeField) you're extending the existing node and place a new field named `localFile` under the `fields` key. - + **Note:** Do not mutate the `node` directly and use `createNodeField` instead. Otherwise the change won't be persisted and you might see inconsistent data. This behavior changed with Gatsby 4, read the [migration guide](/docs/reference/release-notes/migrating-from-v3-to-v4/#dont-mutate-nodes-outside-of-expected-apis) to learn more. diff --git a/docs/docs/reference/release-notes/migrating-source-plugin-from-v3-to-v4.md b/docs/docs/reference/release-notes/migrating-source-plugin-from-v3-to-v4.md index 1223162e917c8..68892749aba2f 100644 --- a/docs/docs/reference/release-notes/migrating-source-plugin-from-v3-to-v4.md +++ b/docs/docs/reference/release-notes/migrating-source-plugin-from-v3-to-v4.md @@ -2,8 +2,6 @@ title: Upgrade Your Source Plugins for Gatsby 4 --- -import { Announcement } from "gatsby-interface" - Gatsby 4 is here! Following on the heels of Gatsby 3, Gatsby 4 further improves build performance and introduces new parallel processing capabilities. In the guide below, we'll walk you through preparing your source plugin for Gatsby 4. You'll find this guide useful if you are a maintainer for a source plugin (as opposed to a consumer using a source plugin in your Gatsby site). Introducing support for Gatsby 4 in your source plugin can be accomplished by ensuring your code adopts the 4 following changes. Many plugins already had the majority of their code organized the way it needed to be! @@ -12,7 +10,7 @@ With Gatsby 4, Core APIs are being split into different processes so they're abl It's time to get into it! The rest of this guide outlines the breaking changes in Gatsby 4 and some quick ways to resolve them. Find something confusing? Let us know in the [GitHub discussion](https://github.com/gatsbyjs/gatsby/discussions/33199) and we'll respond as fast as possible. - + **Looking for examples of source plugins that support Gatsby 4?** Check out [`gatsby-source-wordpress`](/plugins/gatsby-source-wordpress/) and [`gatsby-source-shopify`](/plugins/gatsby-source-shopify/). diff --git a/docs/docs/tutorial/part-0/index.mdx b/docs/docs/tutorial/part-0/index.mdx index f6a0f452e0423..ce2ca3f9fcced 100644 --- a/docs/docs/tutorial/part-0/index.mdx +++ b/docs/docs/tutorial/part-0/index.mdx @@ -3,7 +3,7 @@ title: "Part 0: Set Up Your Development Environment" tableOfContentsDepth: 2 --- -import { Announcement, LinkButton } from "gatsby-interface" +import { LinkButton } from "gatsby-interface" import Collapsible from "@components/collapsible" import { MdArrowForward } from "react-icons/md" @@ -23,7 +23,7 @@ By the end of this part of the Tutorial, you will: The Tutorial is intended to be as approachable as possible for people who are new to Gatsby and React. With that said, if you are brand new to web development (welcome!), you might find it helpful to learn some fundamentals first. - + Don't worry, you don't need to be an expert with these! A high-level understanding of the basics should be enough. You'll pick up a lot through the course of the Tutorial. @@ -94,7 +94,7 @@ brew -v xcode-select --install ``` - + If that fails, download it [directly from Apple's site](https://developer.apple.com/download/more/), after signing-in with an Apple developer account. @@ -111,7 +111,7 @@ If that fails, download it [directly from Apple's site](https://developer.apple. brew install node ``` - + If you don't want to install it through Homebrew, download the latest Node.js version from [the official Node.js website](https://nodejs.org/en/), double click on the downloaded file and go through the installation process. @@ -133,7 +133,7 @@ Download and install the latest Node.js version from [the official Node.js websi Install nvm (Node Version Manager) and needed dependencies. nvm is used to manage Node.js and all its associated versions. - + When installing a package, if it asks for confirmation, type `y` and press enter. @@ -145,7 +145,7 @@ Select your distro: - [Arch, Manjaro and other pacman based distros](#arch-manjaro-and-other-pacman-based-distros) - [Fedora, RedHat, and other dnf based distros](#fedora-redhat-and-other-dnf-based-distros) - + If the Linux distribution you are using is not listed here, please find instructions on the web. @@ -268,7 +268,7 @@ Install the Gatsby CLI globally by running the command below. (Have an older ver npm install -g gatsby-cli ``` - + **Note:** When you install Gatsby and run it for the first time, you'll see a short message notifying you about anonymous usage data that is being collected for Gatsby commands. You can read more about how that data is pulled out and used in the [telemetry doc](/docs/telemetry). @@ -288,9 +288,9 @@ gatsby --help ![Check Gatsby commands in terminal](05-gatsby-help.png) - + -**Troubleshooting** +#### Troubleshooting If you are unable to successfully run the Gatsby CLI due to a permissions issue, you may want to check out the [npm docs on fixing permissions](https://docs.npmjs.com/getting-started/fixing-npm-permissions), or [this guide](https://github.com/sindresorhus/guides/blob/master/npm-global-without-sudo.md). @@ -315,7 +315,7 @@ In this Tutorial, you will deploy your site using Gatsby Cloud. To use Gatsby Cl Now that you have all the knowledge and tools you'll need, you're ready for the Tutorial! - + **Share Your Feedback!** diff --git a/docs/docs/tutorial/part-1/index.mdx b/docs/docs/tutorial/part-1/index.mdx index 71e894089c763..41cc621526366 100644 --- a/docs/docs/tutorial/part-1/index.mdx +++ b/docs/docs/tutorial/part-1/index.mdx @@ -2,7 +2,7 @@ title: "Part 1: Create and Deploy Your First Gatsby Site" --- -import { Announcement, LinkButton } from "gatsby-interface" +import { LinkButton } from "gatsby-interface" import Collapsible from "@components/collapsible" import { MdArrowForward } from "react-icons/md" @@ -30,7 +30,7 @@ First, you write the code for your Gatsby site from your computer. When you're r - + **Prefer a video?** @@ -58,7 +58,7 @@ To create your first Gatsby site, you're going to use a command from the Gatsby ![The welcome message for the interactive "gatsby new" command.](./gatsby-new-cli.png) - + **Note:** For this Tutorial, your Gatsby CLI should be v4.8 or newer. To check what version you have installed, run the following command: @@ -88,7 +88,7 @@ cd Desktop gatsby new ``` - + **Having trouble with `gatsby new`?** If you had trouble globally installing `gatsby-cli` in Part 0, you can also create a new site by running `npm init gatsby` from the command line instead of `gatsby new`. @@ -116,7 +116,7 @@ Will you be using JavaScript or TypeScript? TypeScript ``` - + This tutorial doesn't require any prior TypeScript knowledge as it uses JavaScript. If you're familiar with TypeScript you can read the [Gatsby and TypeScript guide](/docs/how-to/custom-configuration/typescript/) to learn about typings, files, and conventions. If you want to use TypeScript we recommend going through the tutorial first and then only afterwards convert the project to TypeScript. @@ -129,7 +129,7 @@ This tutorial doesn't require any prior TypeScript knowledge as it uses JavaScri Β· No (or I'll add it later) ``` - + In the future, you can use these options to tell `gatsby new` what features you want to add to your site, and `gatsby new` will automatically configure them for you. It's a much quicker way to set up new projects. @@ -196,7 +196,7 @@ To start up your development server, do the following: cd my-first-gatsby-site ``` - + **Tip:** Whenever you want to run any commands for your site, you need to be in the context for that site. That is, your command line needs to be pointed at the directory where your site's code lives. @@ -208,7 +208,7 @@ cd my-first-gatsby-site gatsby develop ``` - + If you weren't able to install the Gatsby command line interface globally, you can start your development server using the following command instead: @@ -239,7 +239,7 @@ And there it is: your very first Gatsby site! πŸŽ‰ You'll be able to visit the site locally at `http://localhost:8000/` for as long as your development server is running. (That's the process you started by running the `gatsby develop` command.) To stop running that process (or to β€œstop running the development server”), go back to your terminal window, hold down the β€œcontrol” key, and then hit β€œc” (`ctrl-c`). To start it again, run `gatsby develop` again! - + **Note:** If you are using VM setup like vagrant and/or would like to listen on your local IP address, run `gatsby develop --host=0.0.0.0`. Now, the development server listens on both `http://localhost` and your local IP. @@ -265,7 +265,7 @@ GitHub is a website that many developers use to back up and share their code onl git push -u origin main ``` - + **Using GitHub for the first time?** @@ -293,7 +293,7 @@ To connect your code on GitHub to your Gatsby Cloud account, do the following: 1. If this is your first time connecting GitHub to Gatsby Cloud, you'll need to give Gatsby Cloud permission to access your GitHub account. - + **Note:** If you are part of more than one GitHub organization, you will need to first select the organization with which the repository resides at this step before selecting the repository itself. @@ -323,7 +323,7 @@ You did it! Your Gatsby site is now online! πŸ‘ Every time you push a new change to the main branch of your GitHub repo, Gatsby Cloud will see the changes and automatically start a build for the new version of your site. - + **Tip:** There will be a unique URL for each build (like `https://build-49535320-b3ae-4761-bbeb-f8f7fa07e0fc.gtsb.io/`), and a URL that always has the latest build (like `my-first-gatsby-site-main.gatsbyjs.io`). You'll mostly want to share the human-readable URL, so that people can always see the most up-to-date version of your site. But in some cases (like when you're trying to debug a specific build of your site) it can be helpful to use the unique build URL. @@ -354,7 +354,7 @@ First, you write the code for your Gatsby site from your computer. When you're r - Gatsby Cloud is an infrastructure platform specifically optimized for building, deploying, and hosting Gatsby sites. - When you push a new commit to the `main` branch of the GitHub repository for your site, Gatsby Cloud will detect the changes, rebuild a new version of your site, and then redeploy it. - + **Share Your Feedback!** diff --git a/docs/docs/tutorial/part-2/index.mdx b/docs/docs/tutorial/part-2/index.mdx index 68b0a3418a302..3edc677073945 100644 --- a/docs/docs/tutorial/part-2/index.mdx +++ b/docs/docs/tutorial/part-2/index.mdx @@ -2,7 +2,7 @@ title: "Part 2: Use and Style React Components" --- -import { Announcement, LinkButton } from "gatsby-interface" +import { LinkButton } from "gatsby-interface" import Collapsible from "@components/collapsible" import { MdArrowForward } from "react-icons/md" @@ -21,7 +21,7 @@ By the end of this part of the Tutorial, you will be able to: - Use component **props** to change the way a component renders. - Use the **`children`** prop to create a wrapper component. - + **Prefer a video?** @@ -57,7 +57,7 @@ To build this page in React, you might have a `` component for the navig You can also create components from other components. For example, you might decide to break down the `` component into a list of multiple `` components, which each display the details about a single product. This pattern is called **composition**, since your larger `` component is _composed_ of smaller `` components. - + **Try it!** @@ -151,7 +151,7 @@ const InvalidComponent = () => { } ``` - + If you try to build your site with the code above, you'll get an error for `` like this: @@ -169,7 +169,7 @@ wrapped in an enclosing tag. Did you want a JSX fragment Now that you've gotten a high-level introduction to React, it's time to try your hands at writing some React components. To start, you'll update the content for the home page. - + If you haven't already, open your Gatsby site in Visual Studio Code, and start up your local development server in the command line: @@ -207,7 +207,7 @@ export default IndexPage ![A screenshot of "localhost:8000" in a web browser. There's a heading that says, "Welcome to my Gatsby site!" and a paragraph that says, "I'm making this by following the Gatsby Tutorial."](./index-page.png) - + **Key Gatsby Concept** πŸ’‘ @@ -262,7 +262,7 @@ export const Head = () => About Me export default AboutPage ``` - + **Key Gatsby Concept** πŸ’‘ @@ -289,7 +289,7 @@ After going through this tutorial, be sure to check out [Adding an SEO Component ![A screenshot of "localhost:8000/about" in a web browser. It has a heading and page title that says, "About Me", and a paragraph that says, "Hi there! I'm the proud creator of this site, which I built with Gatsby."](./about-page.png) - + **Key Gatsby Concept** πŸ’‘ @@ -303,7 +303,7 @@ For example, if you had a file called `src/pages/garden-gnomes.js`, you could ac Now that you've built a few page components, it's time to look at the other type of React components in a Gatsby site: **"building-block" components**. - + **Note:** The term building-block component isn't an official technical term. It's just the best name we could come up with to describe this kind of component. @@ -342,7 +342,7 @@ The code snippets below show an example of how to pass a prop into a component w export default Greeting ``` - + **Syntax Hint:** In JSX, you can embed any JavaScript expression by wrapping it with `{}`. That's how you can access the value of the `name` prop from the `props` object. @@ -377,7 +377,7 @@ The `Link` component is an example of a **pre-built** component that you can use The `Link` component lets you add a link to another page in your Gatsby site. It's similar to an HTML `` tag, but with some extra performance benefits. The `Link` component takes a prop called `to`, which is similar to the `` tag's `href` attribute. The value should be the URL path to the page on your site you want to link to. - + **Key Gatsby Concept** πŸ’‘ @@ -458,7 +458,7 @@ In addition to the props that you can add to your components, React also creates One such prop is called `children`. When you render a component, the `children` prop will automatically be passed whatever content comes between the opening and closing tags for that component. This is helpful when you want to create a component that wraps some generic content. - + The `Link` component you used in the last section also used the `children` prop. You used it to pass in the text to be hyperlinked. @@ -548,7 +548,7 @@ const Layout = ({ pageTitle, children }) => { export default Layout ``` - + **Syntax Hint**: You might have noticed that the `Layout` component uses a slightly different syntax for its props. @@ -716,7 +716,7 @@ const Layout = ({ pageTitle, children }) => { export default Layout ``` - + **Syntax Hint:** To apply classes to React components, use the `className` prop. (This is another example of a built-in prop that React automatically knows how to handle.) @@ -801,7 +801,7 @@ const Layout = ({ pageTitle, children }) => { export default Layout ``` - + **Syntax Hint:** In CSS, the convention is to name classes using kebab case (like `.nav-links`). But in JavaScript, the convention is to name variables using camel case (like `navLinks`). @@ -813,7 +813,7 @@ Luckily, when you use CSS Modules with Gatsby, you can have both! Your kebab-cas ![A screenshot of the Home page. The styles have been updated so now the page title is in purple, and the navigation links at the top of the page are in a single line instead of a bulleted list.](./index-page-styled.png) - + **Want to see how it all fits together?** Check out the finished state of the [GitHub repo for the example site](https://github.com/gatsbyjs/tutorial-example). @@ -832,7 +832,7 @@ Take a moment to think back on what you've learned so far. Challenge yourself to - What are props and when might you use them? - What is the `children` prop and why is it useful? - + **Ship It!** πŸš€ @@ -860,7 +860,7 @@ Once your changes have been pushed to GitHub, Gatsby Cloud should notice the upd - You can use **props** to change how a component renders. You can define your own props when you build a component. React also has some built-in props, like `children` and `className`. - Gatsby isn't opinionated about what styling approach you want to use, but it works with **CSS Modules** by default. - + **Share Your Feedback!** diff --git a/docs/docs/tutorial/part-3/index.mdx b/docs/docs/tutorial/part-3/index.mdx index 00d4a944a8582..ca0bb978564ad 100644 --- a/docs/docs/tutorial/part-3/index.mdx +++ b/docs/docs/tutorial/part-3/index.mdx @@ -3,7 +3,7 @@ title: "Part 3: Add Features with Plugins" tableOfContentsDepth: 2 --- -import { Announcement, LinkButton } from "gatsby-interface" +import { LinkButton } from "gatsby-interface" import Collapsible from "@components/collapsible" import { MdArrowForward } from "react-icons/md" @@ -19,7 +19,7 @@ By the end of this part of the Tutorial, you will be able to: - Add a plugin to your Gatsby site. - Configure your plugins in your `gatsby-config.js` file. - + **Prefer a video?** @@ -111,7 +111,7 @@ module.exports = { } ``` - + **Note:** After you make updates to your `gatsby-config.js` file, you'll need to restart your `gatsby develop` process for your changes to be picked up. @@ -141,7 +141,7 @@ Follow the steps below to use the `StaticImage` component to add an image from a npm install gatsby-plugin-image gatsby-plugin-sharp gatsby-source-filesystem ``` - + The `StaticImage` component requires a few additional plugins to work. These extra plugins are called **peer dependencies**, and you'll need to install them along with the `gatsby-plugin-image` package: @@ -168,7 +168,7 @@ module.exports = { }; ``` - + **Key Gatsby Concept** πŸ’‘ @@ -215,7 +215,7 @@ export default IndexPage ![The home page of your site, which now includes a picture of a dog.](./index-page-with-static-image-from-url.png) - + Nothing at `localhost:8000`? Make sure your local development server is still running! @@ -262,7 +262,7 @@ export default IndexPage ![The home page of your site, which includes a different picture of a dog.](./index-page-with-static-image-from-filesystem.png) - + **Want to see how it all fits together?** Check out the finished state of the [GitHub repo for the example site](https://github.com/gatsbyjs/tutorial-example). @@ -275,7 +275,7 @@ Take a moment to think back on what you've learned so far. Challenge yourself to - What is the benefit to using a plugin in your Gatsby site? - How would you add a new plugin to your Gatsby site? - + **Ship It!** πŸš€ @@ -300,7 +300,7 @@ Once your changes have been pushed to GitHub, Gatsby Cloud should notice the upd - The general process for using a plugin is to install it, configure it in your `gatsby-config.js` file, and then use it in your site as needed. - You can use the [Gatsby Plugin Library](https://www.gatsbyjs.com/plugins) to browse all the available plugins and learn more about how each one works. - + **Share Your Feedback!** diff --git a/docs/docs/tutorial/part-4/index.mdx b/docs/docs/tutorial/part-4/index.mdx index 84a7569eb34ac..6c7031b78ce14 100644 --- a/docs/docs/tutorial/part-4/index.mdx +++ b/docs/docs/tutorial/part-4/index.mdx @@ -2,7 +2,7 @@ title: "Part 4: Query for Data with GraphQL" --- -import { Announcement, LinkButton } from "gatsby-interface" +import { LinkButton } from "gatsby-interface" import Collapsible from "@components/collapsible" import { MdArrowForward } from "react-icons/md" @@ -14,7 +14,7 @@ So far, you've been writing text and adding images directly in your React compon Conveniently, Gatsby has a powerful feature called the **data layer** that you can use to pull data into your site from anywhere. Want to keep your blog posts in WordPress, your store products in Shopify, and your user data in Airtable? No problem! With Gatsby's data layer, you can combine data from multiple sources, which lets you choose the best platform for each type of data. - + Gatsby's data layer is powered by a technology called **GraphQL**. GraphQL is a query language with a special syntax that lets you ask for the data you need inside a component. @@ -32,7 +32,7 @@ By the end of this part of the Tutorial, you will be able to: - Use the **`gatsby-source-filesystem`** plugin to pull data into your site from your computer's filesystem. - Create a **page query** to pull data into a page component. - + **Prefer a video?** @@ -62,7 +62,7 @@ First, your data is stored in one or more **sources**. That source might be a fo How do you get data from its source into the data layer? By adding a type of plugin to your site called a **source plugin**. Each source plugin is designed to communicate with a specific source. When you build your site, each source plugin pulls data from its particular source and adds it to your site's GraphQL data layer. - + **Tip:** Curious what source plugins are in the [Plugin Library](/plugins/)? You can identify source plugins by their name: they typically start with `gatsby-source-`. @@ -154,7 +154,7 @@ Since you don't need to set up a source plugin, you can jump straight into Graph 2. In the Explorer pane, open the dropdown for the `site` field. 3. Within the `site` field, open the _second_ dropdown for the `siteMetadata` field (the blue one). This corresponds to the `siteMetadata` object in your `gatsby-config.js` file. - + **Seeing Double?** @@ -265,7 +265,7 @@ const Header = () => { export default Header ``` - + **Note:** You can only call `useStaticQuery` once per file. If you need multiple fields, you can add them all into a single query. @@ -316,7 +316,7 @@ export default Layout 2. Call `useStaticQuery` and pass it the query you created in GraphiQL. Be sure to use the `graphql` tag so Gatsby knows that the string you're passing in is a GraphQL query. Store the return value from `useStaticQuery` in a variable. - + **Note:** By default, the query you build in GraphiQL will have a query name, like `MyQuery`. You may see an error if you have more than one query with the same name, so after you copy your query over from GraphiQL to your component, delete the name (as in the code example below). @@ -354,7 +354,7 @@ const Layout = ({ pageTitle, children }) => { export default Layout ``` - + **Note:** If you add a line to print out the value of your `data` variable to the console, you'll see that the response has a slightly different structure from what it looked like in GraphiQL's Result Window. Specifically, your `data` variable will only contain the object that matches the `data` field in the Result Window. @@ -589,7 +589,7 @@ export const Head = () => After going through this tutorial, be sure to check out [Adding an SEO Component](/docs/how-to/adding-common-features/adding-seo-component/) for a more detailed explanation. - + **Pro Tip:** `useStaticQuery` lends itself really well when creating small, reusable React components. You can even create custom React hooks, for example: @@ -717,7 +717,7 @@ Now that you have a blog page, it's time to create some blog posts! For your sit Now that you have some posts saved to your local filesystem, it's time to pull those files into the Gatsby data layer. To do that, you'll use a plugin called `gatsby-source-filesystem`. - + **Note:** Remember the process for adding a plugin to your site from [Part 3](/docs/tutorial/part-3)? The first step was to **install** the plugin. @@ -754,7 +754,7 @@ module.exports = { }; ``` - + **A closer look at the configuration options:** @@ -899,7 +899,7 @@ export default BlogPage 2. Define and export your page query. Copy over the query you built in GraphiQL. - + **Note:** By default, the query you build in GraphiQL will have a query name, like `MyQuery`. You may see an error if you have more than one query with the same name, so after you copy your query over from GraphiQL to your component, delete the name (as in the code example below). @@ -940,7 +940,7 @@ export default BlogPage 3. Add in the `data` prop to the function definition. Then replace the placeholder `

` element with a list of the filenames for your posts. Use the JavaScript array `.map()` method to iterate over the `nodes` array and render the filename for each post. - + **Syntax Hint:** In JavaScript, arrays have a built-in [`.map()` method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map), which you can use to iterate over the elements in the array. @@ -989,7 +989,7 @@ export const Head = () => export default BlogPage ``` - + **Pro Tip:** The Gatsby Head API and its `Head` export also receives the `data` prop. This isn't directly obvious when using the component unless your IDE gives autocompletion or hints. If you're unsure how to use an API, head over to the [reference guides](/docs/reference) for instructions. There you'll find guides like [Gatsby Head API](/docs/reference/built-in-components/gatsby-head/). @@ -1011,7 +1011,7 @@ Good job! You've finished the first step of your new blog page. You won't be able to render the contents of your posts just yet, since your site doesn't know how to process MDX. You'll fix that in the next part of the Tutorial! - + **Want to see how it all fits together?** Check out the finished state of the [GitHub repo for the example site](https://github.com/gatsbyjs/tutorial-example). @@ -1026,7 +1026,7 @@ Take a moment to think back on what you've learned so far. Challenge yourself to - How do you get data out of the data layer? - What are the differences between a page query and `useStaticQuery`? How would you decide which one to use? - + **Ship It!** πŸš€ @@ -1066,7 +1066,7 @@ Once your changes have been pushed to GitHub, Gatsby Cloud should notice the upd - + **Share Your Feedback!** diff --git a/docs/docs/tutorial/part-5/index.mdx b/docs/docs/tutorial/part-5/index.mdx index 15bada2137986..e15e0ab63416c 100644 --- a/docs/docs/tutorial/part-5/index.mdx +++ b/docs/docs/tutorial/part-5/index.mdx @@ -2,7 +2,7 @@ title: "Part 5: Transform Data to Use MDX" --- -import { Announcement, LinkButton } from "gatsby-interface" +import { LinkButton } from "gatsby-interface" import Collapsible from "@components/collapsible" import { MdArrowForward } from "react-icons/md" @@ -14,7 +14,7 @@ Sometimes, the format of the data you get from source plugins isn't exactly what In this part of the Tutorial, you'll learn about one particular transformer plugin, `gatsby-plugin-mdx`, which lets you use [MDX](https://mdxjs.com/), a file format that allows Markdown and JSX alongside your text content. (Fun fact: this Tutorial is actually written in MDX!) You'll use MDX to add some content to your blog post files, and then you'll use `gatsby-plugin-mdx` to render the contents of your posts on your Blog page. - + **Note:** Usually, transformer plugin names start with `gatsby-transformer-`. (`gatsby-plugin-mdx` is one exception to this convention.) @@ -28,7 +28,7 @@ By the end of this part of the Tutorial, you will be able to: - Use the `gatsby-plugin-mdx` plugin to render the contents of your MDX files on your Blog page. - Use the `sort` field to control the order of results in your GraphQL queries. - + **Prefer a video?** @@ -60,7 +60,7 @@ A **transformer plugin** converts nodes from one type to another. For example, t ![The gatsby-source-filesystem plugin pulls data from your local filesystem into Gatsby's GraphQL data layer as File nodes. Then the gatsby-plugin-mdx transformer plugin uses those File nodes to create new MDX nodes. Finally, you can use GraphQL queries to pull data from the MDX nodes into your components.](./data-layer-with-nodes.png) - + **Note:** Even though it's called a transformer plugin, it's not actually _changing_ the original nodes created by the source plugins. Each transformer plugin creates new nodes based on the data from the sourced nodes, but it doesn't actually change the source nodes themselves. So even though `gatsby-plugin-mdx` creates new MDX nodes in the data layer, you can still access the original File nodes created by `gatsby-source-filesystem`. @@ -80,7 +80,7 @@ MDX files let you format text using Markdown, a markup language that uses a spec Once you get used to what all the different symbols mean, Markdown can be easier to read than HTML, which makes it a popular format for written content like blog posts. - + **New to Markdown?** The MDX documentation includes a [table of components](https://mdxjs.com/table-of-components) that shows the different formatting options available. It includes things like headings, blockquotes, lists, and code blocks. @@ -152,7 +152,7 @@ Wow look at all this content. How do they do it? Now that you have some MDX content inside your blog posts, it's time set up the `gatsby-plugin-mdx` transformer plugin. - + **Quick Refresher:** Remember the process for adding a plugin to your site (from [Part 3](/docs/tutorial/part-3/))? See if you can remember the three steps from memory before checking your answer. (Science has shown that the act of trying to [actively recall information](https://www.cultofpedagogy.com/retrieval-practice/) helps you retain it better!) @@ -197,7 +197,7 @@ The `gatsby-plugin-mdx` package requires a one additional dependencies to run: ` }; ``` - + **Tip:** There are a variety of [remark](https://remark.js.org/) plugins that you can use to add extra features to your Markdown. You can configure them using the [`gatsbyRemarkPlugins`](/plugins/gatsby-plugin-mdx/#gatsby-remark--plugins) option when you configure `gatsby-plugin-mdx` in your `gatsby-config.js` file. @@ -218,7 +218,7 @@ The `gatsby-plugin-mdx` plugin makes two new fields available for you to use in You can use the `allMdx` field to request data for multiple MDX nodes at once (similar to the way `allFile` worked with File nodes). Open GraphiQL and explore what fields are available on MDX nodes. Try running a few queries to see what kind of information you get back. - + **Quick Refresher:** Remember how to access GraphiQL? See if you can remember the steps before checking for the answer in Part 4. (Check the section called ["Use GraphiQL to explore the data layer and write GraphQL queries"](/docs/tutorial/part-4/#use-graphiql-to-explore-the-data-layer-and-write-graphql-queries)). @@ -240,7 +240,7 @@ Use GraphiQL to create a new query that gets data about your blog posts using th } ``` - + **Syntax Hint:** When it comes to using dates in your frontmatter, the `formatString` argument is a helpful tool for changing the way the date is displayed. @@ -401,7 +401,7 @@ query MyQuery { Now that you have your GraphQL query all set up, it's time to tackle the last piece of the puzzle: rendering your posts in the Blog page. - + **Pro Tip:** When transformer plugins create a new node, they add a `parent` field that references back to the original source node it was created from. For example, when `gatsby-plugin-mdx` creates new MDX nodes, it adds a `parent` field which you can use to access data from the original File node. @@ -569,7 +569,7 @@ export default BlogPage Nice work! Your site now has a blog page with actual content. - + **Want to see how it all fits together?** Check out the finished state of the [GitHub repo for the example site](https://github.com/gatsbyjs/tutorial-example). @@ -582,7 +582,7 @@ Take a moment to think back on what you've learned so far. Challenge yourself to - What is a transformer plugin? How do transformer plugins affect the data in the data layer? - What is MDX? Why is it useful? - + **Ship It!** πŸš€ @@ -607,7 +607,7 @@ Once your changes have been pushed to GitHub, Gatsby Cloud should notice the upd - Transformer plugins create new types of nodes, using data from existing source nodes as a starting point. Transformer plugins don't actually change the original source nodes. - `gatsby-plugin-mdx` is a transformer plugin that lets you use MDX in your site. With MDX, you can create text content with Markdown formatting and embedded React components. - + **Share Your Feedback!** diff --git a/docs/docs/tutorial/part-6/index.mdx b/docs/docs/tutorial/part-6/index.mdx index 3ad78fc545277..ca7322a64cf97 100644 --- a/docs/docs/tutorial/part-6/index.mdx +++ b/docs/docs/tutorial/part-6/index.mdx @@ -2,7 +2,7 @@ title: "Part 6: Create Pages Programmatically" --- -import { Announcement, LinkButton } from "gatsby-interface" +import { LinkButton } from "gatsby-interface" import Collapsible from "@components/collapsible" import { MdArrowForward } from "react-icons/md" @@ -20,7 +20,7 @@ By the end of this part of the Tutorial, you will be able to: - Render the contents of each blog post. - Add a query variable to a page query. - + **Prefer a video?** @@ -121,7 +121,7 @@ You added the information you need to your frontmatter already. If you check the That looks like a good format for a URL! - + **Note:** In this case, the `slug` field is a good choice because it's human readable, which means the URLs for your blog posts will be easier for users to understand. But you can use any field in your routes, even if it contains special characters or whitespace, as Gatsby will ["slugify"](/docs/reference/routing/file-system-route-api/#routing-and-linking) every route when using the File System Route API. For example, `I β™₯ Dogs` will be converted to `i-love-dogs`. @@ -176,7 +176,7 @@ When you build your site, Gatsby looks at the page components in your `src/pages ![A screenshot of the blog post template page in a web browser. The page title says, "Super Cool Blog Posts," and the post contents have a paragraph element that says, "My blog post contents will go here (eventually)."](./post-page-template-hardcoded.png) - + **Pro Tip:** Not sure which pages were created? Check out the 404 page when you run `gatsby develop`. (You can get to it by trying to access the URL for a page that doesn't exist.) The bottom of the page lists the routes for all the pages Gatsby created for your site. @@ -211,7 +211,7 @@ The following diagram shows an overview of the updates you'll have to make in or 3. Once your local development server rebuilds your site, check in a web browser that the paths to your blog posts have updated. - For example, you should now have a page at `localhost:8000/blog/my-first-post/`, and trying to access `localhost:8000/my-first-post/` (without the `blog` path parameter) should send you to the 404 page. - + **Pro Tip:** Gatsby caches information about your site as it builds it, to make subsequent builds faster. But sometimes, when you make changes to your site, you'll need to empty the cache for your changes to show up. @@ -325,7 +325,7 @@ When you use Gatsby's File System Route API, it automatically adds some props in Under the hood, Gatsby makes both of these values available to use as query variables in your page queries. - + **Want to take a closer look?** @@ -360,7 +360,7 @@ The keys in the `pageContext` object get added when you create a page using the } ``` - + **Tip:** If you want to test out your query in GraphiQL, you'll need to add an `id` key to the Query Variables section. You can copy one of the `id` values from running an `allMdx` query in GraphiQL. @@ -515,7 +515,7 @@ The last step of Part 6 is to clean up your Blog page. Instead of rendering an e Congratulations, you now have a multi-page blog site! Try adding some new `.mdx` files to your top-level `blog` directory. They should get added to your Blog page automatically when your site rebuilds! - + **Want to see how it all fits together?** Check out the finished state of the [GitHub repo for the example site](https://github.com/gatsbyjs/tutorial-example). @@ -530,7 +530,7 @@ Take a moment to think back on what you've learned so far. Challenge yourself to - What is a query variable? - When can you use a query variable? - + **Ship It!** πŸš€ @@ -556,7 +556,7 @@ Once your changes have been pushed to GitHub, Gatsby Cloud should notice the upd - Query variables let you pass in different data values to the same GraphQL query. They can be combined with field arguments to get back data only about a specific node. - Query variables can only be used in page queries. - + **Share Your Feedback!** diff --git a/docs/docs/tutorial/part-7/index.mdx b/docs/docs/tutorial/part-7/index.mdx index 8e9852de26773..1cf01796ddd8b 100644 --- a/docs/docs/tutorial/part-7/index.mdx +++ b/docs/docs/tutorial/part-7/index.mdx @@ -2,7 +2,7 @@ title: "Part 7: Add Dynamic Images from Data" --- -import { Announcement, LinkButton } from "gatsby-interface" +import { LinkButton } from "gatsby-interface" import Collapsible from "@components/collapsible" import { MdArrowForward } from "react-icons/md" @@ -16,7 +16,7 @@ By the end of this part of the Tutorial, you will be able to: - Use the `GatsbyImage` component to create images dynamically from data. - + **Prefer a video?** @@ -65,7 +65,7 @@ The steps below will help you find and download some photos for your hero images 1. Start by organizing the `blog` directory with all your MDX posts. First, create a new subdirectory in your `blog` folder for each post. Then, rename each of your `.mdx` files to `index.mdx` (to prevent the routes from ending up with a duplicated path parameter, like `blog/my-post/my-post/`). - For example, a post at `blog/my-first-post.mdx` would move to `blog/my-first-post/index.mdx`. Similarly, a post at `blog/another-post.mdx` would move to `blog/another-post/index.mdx`. - + **Note:** After you move or rename your `.mdx` files, you'll need to stop and restart your local development server for your changes to be picked up. @@ -79,7 +79,7 @@ The steps below will help you find and download some photos for your hero images 3. When you've found a photo that you like, download it and add it to subdirectory for one of your blog posts. Continue downloading photos until you have a different hero image for each post. ![Diagram of the "blog" folder structure, with the hero image for each post in the subdirectory for that post.](./folder-structure-with-images.png) - + **Pro Tip:** Sometimes, the images you download from the internet can be a little _too_ high quality. If you know your site will only ever render an image at 1000 pixels wide, there's no point in having a source image that's 5000 pixels wide. All those extra pixels mean extra work to process and optimize your images, which can slow down build times. @@ -184,7 +184,7 @@ First, you'll use GraphiQL to add the hero image frontmatter fields to the Graph 1. Open GraphiQL by going to `localhost:8000/___graphql` in a web browser. Start by copying your existing blog post page query into the GraphiQL Query Editor pane. Run it once to make sure everything is working correctly. - + **Note:** You'll need to set up an object in the Query Variables pane with an `id` that matches one of your posts. Refer to [Part 6 section on query variables](/docs/tutorial/part-6/#render-post-contents-in-the-blog-post-page-template) if you need a refresher on how to set that up. @@ -217,7 +217,7 @@ query ($id: String) { 2. In the Explorer pane, check the boxes for the `hero_image_alt`, `hero_image_credit_link`, and `hero_image_credit_text` fields. When you run your query, you should get back a response something like the JSON object below. - + **Note:** Remember to scroll down to the blue `frontmatter` field, which is lower than the purple `frontmatter:` argument. @@ -279,7 +279,7 @@ query ($id: String) { } ``` - + **Pro Tip:** How does GraphiQL know to add extra fields to the `hero_image` frontmatter field? @@ -334,7 +334,7 @@ Gatsby can tell that the `hero_image` field from your MDX frontmatter matches a If you take a closer look at the `gatsbyImageData` object on the `hero_image.childImageSharp` field, you'll see that it contains a bunch of information about the hero image for that post: dimensions, file paths for the images at different sizes, fallback images to use as a placeholder while the image loads. All this data gets calculated by `gatsby-plugin-sharp` at build time. The `gatsbyImageData` object in your response has the same structure that the `GatsbyImage` component needs to render an image. - + **Note:** You might have noticed that the `gatsbyImageData` field in GraphiQL accepts several arguments, like `aspectRatio`, `formats`, or `width`. You can use these arguments to pass in extra data about how you want the Sharp image processing library to create your optimized images. @@ -413,7 +413,7 @@ const BlogPost = ({ data, children }) => { // ... ``` - + **Note:** `getImage` is a helper function that takes in a `File` node or an `ImageSharp` node and returns the `gatsbyImageData` object for that node. You can use it to keep your code a little cleaner and easier to read. @@ -452,7 +452,7 @@ Without the `getImage` helper function, you'd have to type out `data.mdx.frontma It's important to give credit to people whose work you use in your own site. The last piece of including hero images to your site is to add a paragraph to give credit to the photographer. - + **Pro Tip:** Since the credit link goes to an external page (in other words, one that's not part of your site), you can use the `` HTML tag instead of the Gatsby `Link` component. @@ -495,7 +495,7 @@ export const Head = ({ data }) => export default BlogPost ``` - + **Syntax Hint:** You might have noticed that there's a `{" "}` after the "Photo Credit:" text `

` tag. That's to make sure that a space gets rendered between the colon (`:`) and the link text. @@ -505,7 +505,7 @@ Try removing the `{" "}` and see what happens. The paragraph text should end up ![A screenshot of the My First Post blog page, which now includes a photo credit underneath the hero image. It says, "Photo Credit: Christopher Ayme".](./blog-post-with-hero-image-credit.png) - + **Want to see how it all fits together?** Check out the finished state of the [GitHub repo for the example site](https://github.com/gatsbyjs/tutorial-example). @@ -517,7 +517,7 @@ Take a moment to think back on what you've learned so far. Challenge yourself to - When should you use the `GatsbyImage` component instead of the `StaticImage` component? - + **Ship It!** πŸš€ @@ -540,7 +540,7 @@ Once your changes have been pushed to GitHub, Gatsby Cloud should notice the upd - Use the `StaticImage` component if your component always renders the same image (from a relative path or a remote URL). - Use the `GatsbyImage` component if the image source changes for different instances of your component (like if it gets passed in as a prop). - + **Share Your Feedback!** From 34574894a25607c0ac2767fd6d1745d73cb7eca2 Mon Sep 17 00:00:00 2001 From: Grayson Hicks Date: Fri, 9 Dec 2022 02:02:44 -0600 Subject: [PATCH 05/92] chore(docs): Add auto config change for `react-dom` in Storybook (#37222) --- .../testing/visual-testing-with-storybook.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/docs/docs/how-to/testing/visual-testing-with-storybook.md b/docs/docs/how-to/testing/visual-testing-with-storybook.md index dfad002f5ad22..a0c4c7c39f63c 100644 --- a/docs/docs/how-to/testing/visual-testing-with-storybook.md +++ b/docs/docs/how-to/testing/visual-testing-with-storybook.md @@ -64,11 +64,18 @@ Storybook's webpack configuration will require adjustments to allow you to trans In your Storybook configuration file (i.e., `.storybook/main.js`) add the following: ```js:title=.storybook/main.js +const React = require("react"); + module.exports = { webpackFinal: async config => { // Transpile Gatsby module because Gatsby includes un-transpiled ES6 code. config.module.rules[0].exclude = [/node_modules\/(?!(gatsby|gatsby-script)\/)/] + // Use correct react-dom depending on React version. + if (parseInt(React.version) <= 18) { + config.externals = ["react-dom/client"]; + } + // Remove core-js to prevent issues with Storybook config.module.rules[0].exclude= [/core-js/] // Use babel-plugin-remove-graphql-queries to remove static queries from components when rendering in storybook @@ -85,6 +92,8 @@ module.exports = { The final `.storybook/main.js` should look something like this: ```js:title=.storybook/main.js +const React = require("react"); + module.exports = { // You will want to change this to wherever your Stories will live stories: ["../src/**/*.stories.mdx", "../src/**/*.stories.@(js|jsx|ts|tsx)"], @@ -98,6 +107,11 @@ module.exports = { // Transpile Gatsby module because Gatsby includes un-transpiled ES6 code. config.module.rules[0].exclude = [/node_modules\/(?!(gatsby|gatsby-script)\/)/] + // Use correct react-dom depending on React version. + if (parseInt(React.version) <= 18) { + config.externals = ["react-dom/client"]; + } + // Remove core-js to prevent issues with Storybook config.module.rules[0].exclude= [/core-js/] // Use babel-plugin-remove-graphql-queries to remove static queries from components when rendering in storybook From dc3d741260e057540ed1294558df78aa63126a8b Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 9 Dec 2022 10:56:43 +0100 Subject: [PATCH 06/92] chore(deps): update dependency prismjs to ^1.29.0 for gatsby-remark-prismjs (#37191) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: LekoArts --- packages/gatsby-remark-prismjs/package.json | 2 +- .../__snapshots__/highlight-code.js.snap | 6 ++-- .../src/__tests__/__snapshots__/index.js.snap | 6 ++-- .../src/__tests__/highlight-code.js | 19 ++-------- .../src/__tests__/index.js | 17 ++------- .../__snapshots__/extend-node.js.snap | 2 +- yarn.lock | 36 +++---------------- 7 files changed, 18 insertions(+), 70 deletions(-) diff --git a/packages/gatsby-remark-prismjs/package.json b/packages/gatsby-remark-prismjs/package.json index 496eb609d467e..cb46d851669da 100644 --- a/packages/gatsby-remark-prismjs/package.json +++ b/packages/gatsby-remark-prismjs/package.json @@ -17,7 +17,7 @@ "babel-preset-gatsby-package": "^3.4.0-next.0", "cheerio": "^1.0.0-rc.10", "cross-env": "^7.0.3", - "prismjs": "^1.21.0", + "prismjs": "^1.29.0", "remark": "^13.0.0" }, "peerDependencies": { diff --git a/packages/gatsby-remark-prismjs/src/__tests__/__snapshots__/highlight-code.js.snap b/packages/gatsby-remark-prismjs/src/__tests__/__snapshots__/highlight-code.js.snap index 0ef4be8a968e6..ce61acf0f9ab9 100644 --- a/packages/gatsby-remark-prismjs/src/__tests__/__snapshots__/highlight-code.js.snap +++ b/packages/gatsby-remark-prismjs/src/__tests__/__snapshots__/highlight-code.js.snap @@ -22,15 +22,15 @@ exports[`highlight code and lines with PrismJS for language jsx 1`] = ` class Counter extends React.Component { constructor() { super() - this.state = { count: 0 } + this.state = { count: 0 } } render() { return ( <div> <h1>Counter</h1> <p>current count: {this.state.count}</p> - <button onClick={() => this.setState({ count: this.state.count + 1 })}> plus + <button onClick={() => this.setState({ count: this.state.count + 1 })}> plus </button> - <button onClick={() => this.setState({ count: this.state.count - 1 })}> + <button onClick={() => this.setState({ count: this.state.count - 1 })}> minus </button> </div> diff --git a/packages/gatsby-remark-prismjs/src/__tests__/__snapshots__/index.js.snap b/packages/gatsby-remark-prismjs/src/__tests__/__snapshots__/index.js.snap index 04fe968cee858..d54c561d21398 100644 --- a/packages/gatsby-remark-prismjs/src/__tests__/__snapshots__/index.js.snap +++ b/packages/gatsby-remark-prismjs/src/__tests__/__snapshots__/index.js.snap @@ -533,7 +533,7 @@ Object { }, "type": "html", "value": "

", }, ], @@ -573,7 +573,7 @@ Object { }, "type": "html", "value": "
//.foo { 
-color: red;
+color: red;
  }\`
", }, ], @@ -613,7 +613,7 @@ Object { }, "type": "html", "value": "
//.foo { 
-color: red;
+color: red;
  }\`
", }, ], diff --git a/packages/gatsby-remark-prismjs/src/__tests__/highlight-code.js b/packages/gatsby-remark-prismjs/src/__tests__/highlight-code.js index 799bc7c177dfd..439d41af0c11b 100644 --- a/packages/gatsby-remark-prismjs/src/__tests__/highlight-code.js +++ b/packages/gatsby-remark-prismjs/src/__tests__/highlight-code.js @@ -88,11 +88,7 @@ export default Counter const language = `text` const code = `