diff --git a/.babelrc.js b/.babelrc.js index 4eb42997a778d..e5e04f5b4fd9e 100644 --- a/.babelrc.js +++ b/.babelrc.js @@ -1,13 +1,13 @@ -let ignore = [`**/dist`] +const ignore = [`**/dist`] // Jest needs to compile this code, but generally we don't want this copied // to output folders -if (process.env.NODE_ENV !== `test`) { - ignore.push(`**/__tests__`) -} +// if (process.env.NODE_ENV !== `test`) { +// ignore.push(`**/__tests__`) +// } module.exports = { sourceMaps: true, - presets: ["babel-preset-gatsby-package"], + presets: [`babel-preset-gatsby-package`], ignore, } diff --git a/.circleci/config.yml b/.circleci/config.yml index e73bd0009df60..b62fb7c0287c8 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -200,7 +200,7 @@ jobs: - run: name: "remove workspaces from package.json" command: | - sed -i ':a;N;$!ba;s/,\n\s*"workspaces":\s\[[^]]*]//g' package.json + sed -i ':a;N;$!ba;s/,\n\s*"workspaces":\s\[[^]]*]/,"workspaces":\["packages\/babel-preset-gatsby"\]/g' package.json - <<: *install_node_modules - run: yarn lint:code - run: yarn lint:docs @@ -309,6 +309,9 @@ jobs: - run: # Quick upgrade to the v2 (any version, we just need the real set version) command: yarn policies set-version berry working_directory: ~/project/e2e-tests/gatsby-pnp + - run: # force typescript to 4.1.5 to pass test + command: sed '$ s/.$/,"resolutions":{"typescript":"4.1.5"}}/' package.json > tmpfile && cat tmpfile > package.json && rm tmpfile + working_directory: ~/project/e2e-tests/gatsby-pnp - run: # Forces to use the local packages command: yarn link --all --private ../.. working_directory: ~/project/e2e-tests/gatsby-pnp diff --git a/.eslintignore b/.eslintignore index 1bd8c9b7ab64e..9468f0f87e4d8 100644 --- a/.eslintignore +++ b/.eslintignore @@ -26,6 +26,7 @@ packages/gatsby/cache-dir/commonjs/**/* packages/gatsby-admin/public packages/gatsby/gatsby-admin-public packages/gatsby-codemods/transforms +packages/gatsby-source-graphql/batching packages/gatsby-source-wordpress/test-site/** !packages/gatsby-source-wordpress/test-site/__tests__ diff --git a/.eslintrc.js b/.eslintrc.js index 0e801b4351173..d2415067377b8 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -1,23 +1,22 @@ -const TSEslint = require("@typescript-eslint/eslint-plugin") - module.exports = { - parser: "babel-eslint", + parser: `@babel/eslint-parser`, extends: [ - "google", - "eslint:recommended", - "plugin:flowtype/recommended", - "plugin:react/recommended", - "prettier", - "prettier/flowtype", - "prettier/react", + `google`, + `eslint:recommended`, + `plugin:flowtype/recommended`, + `plugin:react/recommended`, + `prettier`, ], - plugins: ["flowtype", "prettier", "react", "filenames"], + plugins: [`flowtype`, `prettier`, `react`, `filenames`, `@babel`], parserOptions: { ecmaVersion: 2016, - sourceType: "module", + sourceType: `module`, ecmaFeatures: { jsx: true, }, + babelOptions: { + configFile: `./.babelrc.js`, + }, }, env: { browser: true, @@ -39,43 +38,63 @@ module.exports = { __ASSET_PREFIX__: true, }, rules: { - "arrow-body-style": [ - "error", - "as-needed", - { requireReturnForObjectLiteral: true }, - ], - "no-unused-expressions": [ - "error", + "@babel/no-unused-expressions": [ + `error`, { allowTaggedTemplates: true, }, ], + "no-unused-expressions": `off`, + "@babel/no-invalid-this": `error`, + "no-invalid-this": `off`, + "arrow-body-style": [ + `error`, + `as-needed`, + { requireReturnForObjectLiteral: true }, + ], + "new-cap": `off`, "no-unused-vars": [ - "warn", + `warn`, { - varsIgnorePattern: "^_", - argsIgnorePattern: "^_", + varsIgnorePattern: `^_`, + argsIgnorePattern: `^_`, ignoreRestSiblings: true, }, ], - "consistent-return": ["error"], - "filenames/match-regex": ["error", "^[a-z-\\d\\.]+$", true], - "no-console": "off", - "no-inner-declarations": "off", - "prettier/prettier": "error", - quotes: ["error", "backtick"], - "react/display-name": "off", - "react/jsx-key": "warn", - "react/no-unescaped-entities": "off", - "react/prop-types": "off", - "require-jsdoc": "off", - "valid-jsdoc": "off", + "consistent-return": [`error`], + "filenames/match-regex": [`error`, `^[a-z-\\d\\.]+$`, true], + "no-console": `off`, + "no-inner-declarations": `off`, + "prettier/prettier": `error`, + quotes: [`error`, `backtick`], + "react/display-name": `off`, + "react/jsx-key": `warn`, + "react/no-unescaped-entities": `off`, + "react/prop-types": `off`, + "require-jsdoc": `off`, + "valid-jsdoc": `off`, + "prefer-promise-reject-errors": `warn`, + "no-prototype-builtins": `warn`, + "guard-for-in": `warn`, + "spaced-comment": [ + `error`, + `always`, + { markers: [`/`], exceptions: [`*`, `+`] }, + ], + camelcase: [ + `error`, + { + properties: `never`, + ignoreDestructuring: true, + allow: [`^unstable_`], + }, + ], }, overrides: [ { files: [ - "packages/**/gatsby-browser.js", - "packages/gatsby/cache-dir/**/*", + `packages/**/gatsby-browser.js`, + `packages/gatsby/cache-dir/**/*`, ], env: { browser: true, @@ -86,65 +105,106 @@ module.exports = { }, }, { - files: ["**/cypress/integration/**/*", "**/cypress/support/**/*"], + files: [`**/cypress/integration/**/*`, `**/cypress/support/**/*`], globals: { cy: false, Cypress: false, }, }, { - files: ["*.ts", "*.tsx"], - parser: "@typescript-eslint/parser", - plugins: ["@typescript-eslint/eslint-plugin"], + files: [`*.ts`, `*.tsx`], + parser: `@typescript-eslint/parser`, + plugins: [`@typescript-eslint/eslint-plugin`], + extends: [`plugin:@typescript-eslint/recommended`], rules: { - ...TSEslint.configs.recommended.rules, // We should absolutely avoid using ts-ignore, but it's not always possible. // particular when a dependencies types are incorrect. - "@typescript-eslint/ban-ts-comment": { - "ts-ignore": "allow-with-description", - }, + "@typescript-eslint/ban-ts-comment": [ + `warn`, + { "ts-ignore": `allow-with-description` }, + ], // This rule is great. It helps us not throw on types for areas that are // easily inferrable. However we have a desire to have all function inputs // and outputs declaratively typed. So this let's us ignore the parameters // inferrable lint. "@typescript-eslint/no-inferrable-types": [ - "error", + `error`, { ignoreParameters: true }, ], "@typescript-eslint/ban-types": [ - "error", + `error`, { extendDefaults: true, types: { "{}": { - fixWith: "Record", + fixWith: `Record`, }, object: { - fixWith: "Record", + fixWith: `Record`, }, }, }, ], + camelcase: `off`, + // TODO: These rules allow a lot of stuff and don't really enforce. If we want to apply our styleguide, we'd need to fix a lot of stuff "@typescript-eslint/naming-convention": [ + `error`, + { + selector: `default`, + format: [`camelCase`], + }, + { + selector: `variable`, + format: [`camelCase`, `UPPER_CASE`, `PascalCase`], + leadingUnderscore: `allowSingleOrDouble`, + trailingUnderscore: `allowSingleOrDouble`, + }, + { + selector: `function`, + format: [`camelCase`, `PascalCase`], + leadingUnderscore: `allow`, + }, + { + selector: `parameter`, + format: [`camelCase`, `PascalCase`, `snake_case`], + leadingUnderscore: `allowSingleOrDouble`, + }, + { + selector: `enumMember`, + format: [`camelCase`, `UPPER_CASE`, `PascalCase`], + }, + { + selector: `typeLike`, + format: [`PascalCase`], + }, + { + selector: `typeAlias`, + format: [`camelCase`, `PascalCase`], + }, + { + selector: `property`, + format: [`PascalCase`, `UPPER_CASE`, `camelCase`, `snake_case`], + leadingUnderscore: `allowSingleOrDouble`, + }, { - selector: "default", - format: ["camelCase"], + selector: `objectLiteralProperty`, + format: [`PascalCase`, `UPPER_CASE`, `camelCase`, `snake_case`], + leadingUnderscore: `allowSingleOrDouble`, + trailingUnderscore: `allowSingleOrDouble`, }, - { selector: "variable", format: ["camelCase", "UPPER_CASE"] }, { - selector: "parameter", - format: ["camelCase"], - leadingUnderscore: "allow", - prefix: ["unstable_", ""], + selector: `enum`, + format: [`PascalCase`, `UPPER_CASE`], }, { - selector: "typeLike", - format: ["PascalCase"], + selector: `method`, + format: [`PascalCase`, `camelCase`], + leadingUnderscore: `allowSingleOrDouble`, }, { - selector: "interface", - format: ["PascalCase"], - prefix: ["I"], + selector: `interface`, + format: [`PascalCase`], + prefix: [`I`], }, ], // This rule tries to prevent using `require()`. However in node code, @@ -152,7 +212,8 @@ module.exports = { // problems in our tests where we often want this functionality for module // mocking. At this point it's easier to have it off and just encourage // using top-level imports via code reviews. - "@typescript-eslint/no-var-requires": "off", + "@typescript-eslint/no-var-requires": `off`, + "@typescript-eslint/no-extra-semi": `off`, // This rule ensures that typescript types do not have semicolons // at the end of their lines, since our prettier setup is to have no semicolons // e.g., @@ -160,52 +221,51 @@ module.exports = { // - baz: string; // + baz: string // } - "@typescript-eslint/no-extra-semi": false, "@typescript-eslint/member-delimiter-style": [ - "error", + `error`, { multiline: { - delimiter: "none", + delimiter: `none`, }, }, ], - "@typescript-eslint/no-empty-function": "off", + "@typescript-eslint/no-empty-function": `off`, // This ensures that we always type the return type of functions // a high level focus of our TS setup is typing fn inputs and outputs. - "@typescript-eslint/explicit-function-return-type": "error", + "@typescript-eslint/explicit-function-return-type": `error`, // This forces us to use interfaces over types aliases for object definitions. // Type is still useful for opaque types // e.g., // type UUID = string "@typescript-eslint/consistent-type-definitions": [ - "error", - "interface", + `error`, + `interface`, ], "@typescript-eslint/no-use-before-define": [ - "error", + `error`, { functions: false }, ], // Allows us to write unions like `type Foo = "baz" | "bar"` // otherwise eslint will want to switch the strings to backticks, // which then crashes the ts compiler - quotes: "off", + quotes: `off`, "@typescript-eslint/quotes": [ 2, - "backtick", + `backtick`, { avoidEscape: true, }, ], // bump to @typescript-eslint/parser started showing Flow related errors in ts(x) files // so disabling them in .ts(x) files - "flowtype/no-types-missing-file-annotation": "off", - "@typescript-eslint/array-type": ["error", { default: "generic" }], + "flowtype/no-types-missing-file-annotation": `off`, + "@typescript-eslint/array-type": [`error`, { default: `generic` }], }, }, ], settings: { react: { - version: "16.9.0", + version: `16.9.0`, }, }, } diff --git a/README.md b/README.md index cb1bdae24a31a..6d976582cb1fd 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@

- Gatsby v2 + Gatsby v3

@@ -36,7 +36,7 @@ PRs welcome! - Follow @gatsbyjs + Follow @GatsbyJS

@@ -52,8 +52,8 @@ Showcase · Contribute - · - Support: Twitter +
+ Support: Twitter, Discussions & Discord

@@ -61,7 +61,7 @@ Gatsby is a modern web framework for blazing fast websites. - **Go Beyond Static Websites.** Get all the benefits of static websites with none of the - limitations. Gatsby sites are fully functional React apps so you can create high-quality, + limitations. Gatsby sites are fully functional React apps, so you can create high-quality, dynamic web apps, from blogs to e-commerce sites to user dashboards. - **Use a Modern Stack for Every Site.** No matter where the data comes from, Gatsby sites are @@ -76,9 +76,9 @@ Gatsby is a modern web framework for blazing fast websites. splitting, image optimization, inlining critical styles, lazy-loading, prefetching resources, and more to ensure your site is fast — no manual tuning required. -- **Host at Scale for Pennies.** Gatsby sites don’t require servers so you can host your entire +- **Host at Scale for Pennies.** Gatsby sites don’t require servers, so you can host your entire site on a CDN for a fraction of the cost of a server-rendered site. Many Gatsby sites can be - hosted entirely free on services like GitHub Pages and Netlify. + hosted entirely free on [Gatsby Cloud](https://www.gatsbyjs.com/cloud/) and other similar services. [**Learn how to use Gatsby for your next project.**](https://www.gatsbyjs.com/docs/) @@ -88,8 +88,8 @@ Gatsby is a modern web framework for blazing fast websites. - [Learning Gatsby](#-learning-gatsby) - [Migration Guides](#-migration-guides) - [How to Contribute](#-how-to-contribute) -- [License](#memo-license) -- [Thanks to Our Contributors and Sponsors](#-thanks) +- [License](#-license) +- [Thanks to Our Contributors](#-thanks) ## 🚀 Get Up and Running in 5 Minutes @@ -99,7 +99,6 @@ You can get a new Gatsby site up and running on your local dev environment in 5 ```shell npm install -g gatsby-cli - ``` 2. **Create a Gatsby site from a Gatsby starter.** @@ -107,8 +106,9 @@ You can get a new Gatsby site up and running on your local dev environment in 5 Get your Gatsby blog set up in a single command: ```shell - # create a new Gatsby site using the default starter - gatsby new my-blazing-fast-site + # Create a new Gatsby site using the interactive setup wizard + # Give it this name: My Gatsby site + gatsby new ``` 3. **Start the site in `develop` mode.** @@ -116,13 +116,13 @@ You can get a new Gatsby site up and running on your local dev environment in 5 Next, move into your new site’s directory and start it up: ```shell - cd my-blazing-fast-site/ + cd my-gatsby-site/ gatsby develop ``` 4. **Open the source code and start editing!** - Your site is now running at `http://localhost:8000`. Open the `my-blazing-fast-site` directory in your code editor of choice and edit `src/pages/index.js`. Save your changes, and the browser will update in real time! + Your site is now running at `http://localhost:8000`. Open the `my-gatsby-site` directory in your code editor of choice and edit `src/pages/index.js`. Save your changes, and the browser will update in real time! At this point, you’ve got a fully functional Gatsby website. For additional information on how you can customize your Gatsby site, see our [plugins](https://gatsbyjs.com/plugins/) and [the official tutorial](https://www.gatsbyjs.com/tutorial/). @@ -132,7 +132,7 @@ Full documentation for Gatsby lives [on the website](https://www.gatsbyjs.com/). - **For most developers, we recommend starting with our [in-depth tutorial for creating a site with Gatsby](https://www.gatsbyjs.com/tutorial/).** It starts with zero assumptions about your level of ability and walks through every step of the process. -- **To dive straight into code samples head [to our documentation](https://www.gatsbyjs.com/docs/).** In particular, check out the “Guides”, “API Reference”, and “Advanced Tutorials” sections in the sidebar. +- **To dive straight into code samples head [to our documentation](https://www.gatsbyjs.com/docs/).** In particular, check out the “How-to Guides”, “Reference”, and “Conceptual Guides” sections in the sidebar. We welcome suggestions for improving our docs. See the [“how to contribute”](https://www.gatsbyjs.com/contributing/how-to-contribute/) documentation for more details. @@ -140,10 +140,10 @@ We welcome suggestions for improving our docs. See the [“how to contribute”] ## 💼 Migration Guides -Already have a Gatsby site? These handy guides will help you add the improvements of Gatsby v2 to your site without starting from scratch! +Already have a Gatsby site? These handy guides will help you add the improvements of Gatsby v3 to your site without starting from scratch! -- [Migrate a Gatsby site from v1 to v2](https://www.gatsbyjs.com/docs/migrating-from-v1-to-v2/) -- Still on v0? Start here: [Migrate a Gatsby site from v0 to v1](https://www.gatsbyjs.com/docs/migrating-from-v0-to-v1/) +- [Migrate from v2 to v3](https://www.gatsbyjs.com/docs/reference/release-notes/migrating-from-v2-to-v3/) +- [Migrate from v1 to v2](https://www.gatsbyjs.com/docs/reference/release-notes/migrating-from-v1-to-v2/) ## ❗ Code of Conduct @@ -157,16 +157,21 @@ Check out our [**Contributing Guide**](https://www.gatsbyjs.com/contributing/how ### A note on how this repository is organized -This repository is a [monorepo](https://trunkbaseddevelopment.com/monorepos/) managed using [Lerna](https://github.com/lerna/lerna). This means there are [multiple packages](/packages) managed in this codebase, even though we publish them to NPM as separate packages. +This repository is a [monorepo](https://trunkbaseddevelopment.com/monorepos/) managed using [Lerna](https://github.com/lerna/lerna). This means there are [multiple packages](https://github.com/gatsbyjs/gatsby/tree/master/packages) managed in this codebase, even though we publish them to NPM as separate packages. -### Contributing to Gatsby v1 +### Contributing to Gatsby v2 -We are currently only accepting bug fixes for Gatsby v1. No new features will be accepted. +The maintenance window for Gatsby v2 closes on April 1, 2021. -## :memo: License +- During this maintenance window, we will continue to address reported bugs in Gatsby v2. +- After the maintenance window closes, we will only accept critical security updates for Gatsby v2. + +## 📝 License Licensed under the [MIT License](./LICENSE). ## 💜 Thanks -Thanks to our many contributors and to [Netlify](https://www.netlify.com/) for hosting [Gatsby](https://www.gatsbyjs.com) and our example sites. +Thanks goes out to all our many contributors creating plugins, starters, videos, and blog posts. And a special appreciation for our community members helping with issues and PRs, or answering questions on Discord and GitHub Discussions. + +A big part of what makes Gatsby great is each and every one of you in the community. Your contributions enrich the Gatsby experience and make it better every day. diff --git a/deprecated-packages/gatsby-plugin-guess-js/src/gatsby-ssr.js b/deprecated-packages/gatsby-plugin-guess-js/src/gatsby-ssr.js index bb32ba5feccb7..4a8817d640564 100644 --- a/deprecated-packages/gatsby-plugin-guess-js/src/gatsby-ssr.js +++ b/deprecated-packages/gatsby-plugin-guess-js/src/gatsby-ssr.js @@ -41,7 +41,7 @@ exports.onRenderBody = ( matchedPages.forEach(p => { if (p && p.componentChunkName) { const fetchKey = `assetsByChunkName[${p.componentChunkName}]` - let chunks = _.get(stats, fetchKey) + const chunks = _.get(stats, fetchKey) componentUrls = [...componentUrls, ...chunks] } }) diff --git a/dictionary.txt b/dictionary.txt index 33ebb849130f2..a3128df9abcb8 100644 --- a/dictionary.txt +++ b/dictionary.txt @@ -58,7 +58,6 @@ APIs APIs. AppSync architecting -Archlinux arg args args. @@ -270,7 +269,6 @@ devcert devcert-cli devDependencies developMiddleware -Devops DevOps DevTools Dgraph diff --git a/docs/docs/conceptual/choosing-a-cms.md b/docs/docs/conceptual/choosing-a-cms.md index 51764bbbe26c6..9d8e96fb10d05 100644 --- a/docs/docs/conceptual/choosing-a-cms.md +++ b/docs/docs/conceptual/choosing-a-cms.md @@ -28,7 +28,7 @@ In terms of popularity, you can see [top integrations listed by monthly download - If you're working on a personal project or prototype, a few of these have a generous free tier (Contentful, DatoCMS, Prismic, Sanity, Strapi). -- If you're looking more at "Team", "Pro", or "Business" price points (eg $29, $99, or \$299 per month), the above CMSs are all good options, plus Drupal and WordPress. +- If you're looking more at "Team", "Pro", or "Business" price points (e.g. $29, $99, or \$299 per month), the above CMSs are all good options, plus Drupal and WordPress. - If you're looking more at an "enterprise" project in the four digits per month and up, your main options are Contentful, Contentstack, Sanity, and Strapi. diff --git a/docs/docs/conceptual/gatsby-core-philosophy.md b/docs/docs/conceptual/gatsby-core-philosophy.md index 3119969b1617c..a08d427a3618f 100644 --- a/docs/docs/conceptual/gatsby-core-philosophy.md +++ b/docs/docs/conceptual/gatsby-core-philosophy.md @@ -21,7 +21,7 @@ Today's building blocks for the web are components of HTML, CSS, and JavaScript. We believe that in 5 or 10 years, we'll look back at many of these blocks like we look back at machine code or assembly language today; low-level languages that are great compile targets for higher-level languages that are easier to write in. -Using abstractions like React components, `gatsby-image`, and `gatsby-link`, we've begun to craft this higher-level language. But we're just getting started. Gatsby is a playground for discovering new building blocks for the web. +Using abstractions like React components, `gatsby-plugin-image`, and `gatsby-link`, we've begun to craft this higher-level language. But we're just getting started. Gatsby is a playground for discovering new building blocks for the web. To [quote Alan Kay](https://www.youtube.com/watch?v=NdSD07U5uBs): @@ -97,7 +97,7 @@ If you were designing a user interface, you might move advanced or rarely-used f Progressive disclosure simplifies the experience for most people without limiting the abilities of more advanced users. -We progressively disclose complexity by making features such as modifying webpack / Babel config, `gatsby-image`, and `gatsby-link` opt-in, simple one-off configuration choices. We avoid all-or-nothing "ejection" scenarios where to add further customization you have to leave the tool behind and manage all complexity (e.g. dependencies) yourself. +We progressively disclose complexity by making features such as modifying webpack / Babel config, `gatsby-plugin-image`, and `gatsby-link` opt-in, simple one-off configuration choices. We avoid all-or-nothing "ejection" scenarios where to add further customization you have to leave the tool behind and manage all complexity (e.g. dependencies) yourself. [Read more here](https://lengstorf.com/progressive-disclosure-of-complexity/). diff --git a/docs/docs/conceptual/gatsby-for-ecommerce.md b/docs/docs/conceptual/gatsby-for-ecommerce.md index 769a896d4321f..dc2688d945f8d 100644 --- a/docs/docs/conceptual/gatsby-for-ecommerce.md +++ b/docs/docs/conceptual/gatsby-for-ecommerce.md @@ -10,7 +10,7 @@ The website functions because these front-end capabilities integrate with a wide ### Choosing a main e-commerce platform -Most businesses choose a central e-commerce platform as their source of truth for these functionality. Some businesses choose to run entirely on these platforms, which can be quicker to get started with but lock you in to their choices for website creation (eg Liquid Templates for Shopify). +Most businesses choose a central e-commerce platform as their source of truth for these functionality. Some businesses choose to run entirely on these platforms, which can be quicker to get started with but lock you in to their choices for website creation (e.g. Liquid Templates for Shopify). If you're using or considering Gatsby, your organization is likely optimizing for specific properties of your website (such as performance, development environment, design, user experience, and security) and are therefore considering a "JAMstack", "decoupled" or "content mesh" architecture. @@ -35,7 +35,7 @@ E-commerce tends to have a number of specific requirements. When building a Gats - **Persisting a cart across site pages and between sessions** (ie, if the user closes their browser and reopens it tomorrow, the items should still be there). This can be handled either through local-storage or through the shopify-buy JS library. - **Product search** can be done client-side if the SKU count is small enough to store all products in a global state. Alternatively, it can be handled through the e-commerce provider’s search features, or if those aren’t robust enough, a third-party search provider like Algolia. - **Surfacing price adjustments** like tax, shipping, discounts/promos to the user while browsing the site. Different e-commerce solutions provide different levels of API access to these objects. -- **Handling checkout.** In order to comply with PCI regulations around storing credit card information, e-commerce providers typically exert strong control over the "buy" or "checkout" experience. Shopify requires all checkout flows using their platform to use their hosted checkout pages, though it's common to wrap them in a subdomain of the main site (eg the Gatsby/Shopify site [strivectin.com](strivectin.com] wraps a `myshopify.com` URL under a `shop.strivectin.com` URL for checkout). +- **Handling checkout.** In order to comply with PCI regulations around storing credit card information, e-commerce providers typically exert strong control over the "buy" or "checkout" experience. Shopify requires all checkout flows using their platform to use their hosted checkout pages, though it's common to wrap them in a subdomain of the main site (e.g. the Gatsby/Shopify site [strivectin.com](strivectin.com] wraps a `myshopify.com` URL under a `shop.strivectin.com` URL for checkout). - **Handling account pages.** Again, many sites choose to wrap their e-commerce provider’s account pages under their own domain. Additional resources: diff --git a/docs/docs/conceptual/using-gatsby-image.md b/docs/docs/conceptual/using-gatsby-image.md index d49a4036a32dd..d045e127a74e9 100644 --- a/docs/docs/conceptual/using-gatsby-image.md +++ b/docs/docs/conceptual/using-gatsby-image.md @@ -14,9 +14,9 @@ One important part of overall page loading experience is image loading. There ar - **Minimize image file size to reduce request roundtrip time.** There are a number of ways, from cropping overly large images, to using newer file types, to reduce image file size. -We built Gatsby Image to provide these things -- a [higher-level building block](https://www.gatsbyjs.com/docs/conceptual/gatsby-core-philosophy/#construct-new-higher-level-web-building-blocks) that has the richness users expect, with the API simplicity developers love (and without maintaining your own image processing pipeline!). +We built Gatsby Image to provide these things -- a [higher-level building block](/docs/conceptual/gatsby-core-philosophy/#construct-new-higher-level-web-building-blocks) that has the richness users expect, with the API simplicity developers love (and without maintaining your own image processing pipeline!). -We provide a [detailed guide on using Gatsby Image](docs/how-to/images-and-media/using-gatsby-image/) in the How To section of this documentation. Here, we walk through the question of why these benefits matter, from a user's perspective, and why providing them without Gatsby Image (or something similar) can be difficult. +We provide a [detailed guide on using Gatsby Image](/docs/how-to/images-and-media/using-gatsby-plugin-image/) in the How To section of this documentation. Here, we walk through the question of why these benefits matter, from a user's perspective, and why providing them without Gatsby Image (or something similar) can be difficult. ## Fetch above-the-fold images immediately @@ -50,7 +50,7 @@ When a browser doesn't know how big an image is going to be, either because the ### Gradual color transition -In addition, when an image appears, it goes from blank background to fully there from one frame to another. This can also be visually jarring. Like css has a `transition` prop to help position shifts feel gradual, images feel more aesthetically pleasing when they have placeholders. +In addition, when an image appears, it goes from blank background to fully there from one frame to another. This can also be visually jarring. Like CSS has a `transition` prop to help position shifts feel gradual, images feel more aesthetically pleasing when they have placeholders. Gatsby Image's will hold the spot for your image automatically when you specify `width` prop, and depending on your preference, will provide a background -- blurred, a background color, or traced SVG, while the image loads. @@ -66,7 +66,7 @@ A common problem in larger projects is that images are uploaded into a CMS by co For example, a support staff member may take a 1600x2000 pixel screenshot, save it as a PNG, and upload it alongside a helpdesk article. While this is a quite reasonable action, it may degrade page performance significantly. If the article has a 800px maximum width, a 640 x 800 pixel JPG would have displayed at the same quality but a tenth of the size; the extra weight may delay page load by a second or two. -You can solve this on your own via creating and maintaining a custom image processing pipeline, perhaps during CI/CD, to resize. However, that requires writing, and then maintaining, custom code. Gatsby Image solves this out of the box; if you use the `width` or `maxWidth` prop, Gatsby Image will automatically resize larger underlying assets. +You can solve this on your own via creating and maintaining a custom image processing pipeline, perhaps during CI/CD, to resize. However, that requires writing, and then maintaining, custom code. Gatsby Image solves this out of the box; if you use the `width` prop, Gatsby Image will automatically resize larger underlying assets. ### Generating "responsive images" for different device sizes @@ -80,6 +80,6 @@ In order to support responsive images, you need to do the image processing befor ### Better compression -The new [WebP image](https://developers.google.com/speed/webp) standard reduces image size by 25-35% for modern browsers. It's possible to support this standard, but you also need to fall back for older browsers that don't support this, which without framework support adds additional complexity. +The new [WebP image](https://developers.google.com/speed/webp) standard reduces image size by 25-35% for modern browsers. Additionally, [AVIF Images](https://netflixtechblog.com/avif-for-next-generation-image-coding-b1d75675fe4) are also supported. AVIF is a brand new image format, which offers considerably better filesizes and quality than JPG and even WebP. It's possible to support these standards, but you also need to fall back for older browsers that don't support this, which without framework support adds additional complexity. -Gatsby supports WebP out of the box as a setting on Gatsby Image. +Gatsby supports WebP & AVIF out of the box as a setting on Gatsby Image. diff --git a/docs/docs/deploying-to-digitalocean-droplet.md b/docs/docs/deploying-to-digitalocean-droplet.md index 66c04bce0f3a7..6c21fda9f93d8 100644 --- a/docs/docs/deploying-to-digitalocean-droplet.md +++ b/docs/docs/deploying-to-digitalocean-droplet.md @@ -30,7 +30,7 @@ Follow these instructions for installs on an Ubuntu droplet. ```shell sudo apt-get update - sudo apt-get install node + sudo apt-get install nodejs ``` 3. Install npm @@ -42,7 +42,7 @@ Follow these instructions for installs on an Ubuntu droplet. To view the version of Node.js and npm installed, run, ```shell - node -v + nodejs -v npm -v ``` @@ -57,7 +57,7 @@ Follow these instructions for installs on an Ubuntu droplet. > You can either exit and restart your terminal or refresh the cache by running the following commands: ```shell - hash node + hash nodejs hash npm ``` @@ -249,7 +249,7 @@ There's a lot more to learn about DigitalOcean's Droplets, Ubuntu configurations - [Microblog - Create a new non-root user with `sudo` privileges on Ubuntu-based DigitalOcean Droplet configured with SSH](https://dev.to/mistryvatsal/microblog-create-a-new-non-root-user-with-sudo-privileges-on-ubuntu-based-digitalocean-droplet-configured-with-ssh-1l3) - [Official DigitalOcean Docs](https://www.digitalocean.com/docs/) -- [Official Nginx Docs](http://nginx.org/en/docs/) -- [Configuring HTTPS Servers with Nginx](http://nginx.org/en/docs/http/configuring_https_servers.html) +- [Official Nginx Docs](https://nginx.org/en/docs/) +- [Configuring HTTPS Servers with Nginx](https://nginx.org/en/docs/http/configuring_https_servers.html) - [How To Install Nginx on Ubuntu 18.04](https://www.digitalocean.com/community/tutorials/how-to-install-nginx-on-ubuntu-18-04) - [How To Secure Nginx with Let's Encrypt on Ubuntu 18.04](https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-18-04) diff --git a/docs/docs/deploying-to-gitlab-pages.md b/docs/docs/deploying-to-gitlab-pages.md index 35d0d37c65674..390142c2db7c1 100644 --- a/docs/docs/deploying-to-gitlab-pages.md +++ b/docs/docs/deploying-to-gitlab-pages.md @@ -41,7 +41,7 @@ If adding this manually to your project, the file needs to contain a few require image: node:latest # This folder is cached between builds -# http://docs.gitlab.com/ce/ci/yaml/README.html#cache +# https://docs.gitlab.com/ce/ci/yaml/README.html#cache cache: paths: - node_modules/ diff --git a/docs/docs/glossary/continuous-deployment.md b/docs/docs/glossary/continuous-deployment.md index c0d6d7d97d61a..b3ab7fc6b5916 100644 --- a/docs/docs/glossary/continuous-deployment.md +++ b/docs/docs/glossary/continuous-deployment.md @@ -7,7 +7,7 @@ disableTableOfContents: true Continuous deployment (CD) is the automation of code deployments. In a continuous deployment system, you don't push a Deploy button or run a `deploy` command. Instead, you build a _pipeline_ — a process that [builds](/docs/glossary/build/) and releases code automatically, without human intervention. -You'll most likely use a service to create your continuous deployment pipeline. Services such as [Netlify](http://netlify.com/), [AWS Amplify](https://aws.amazon.com/amplify/), [Azure](https://azure.microsoft.com/en-us/), and [Vercel](https://vercel.com/) are popular with Gatsby users. Or you can use [Gatsby Builds](/blog/2020-01-27-announcing-gatsby-builds-and-reports/), a feature of the [Gatsby Cloud](https://www.gatsbyjs.com/) service. +You'll most likely use a service to create your continuous deployment pipeline. Services such as [Netlify](https://www.netlify.com/), [AWS Amplify](https://aws.amazon.com/amplify/), [Azure](https://azure.microsoft.com/en-us/), and [Vercel](https://vercel.com/) are popular with Gatsby users. Or you can use [Gatsby Builds](/blog/2020-01-27-announcing-gatsby-builds-and-reports/), a feature of the [Gatsby Cloud](https://www.gatsbyjs.com/) service. A continuous deployment pipeline begins with a [Git](https://git-scm.com/) repository. Git is source control management software, and you use it to manage changes to your site's code. Most continuous deployment services require a hosted Git service such as [GitHub](https://github.com/), [GitLab](https://about.gitlab.com/), or [Bitbucket](https://bitbucket.org/). diff --git a/docs/docs/glossary/headless-wordpress.md b/docs/docs/glossary/headless-wordpress.md index 0f588b1c5af9d..07449c971fe4a 100644 --- a/docs/docs/glossary/headless-wordpress.md +++ b/docs/docs/glossary/headless-wordpress.md @@ -7,7 +7,7 @@ Learn what headless WordPress means, how it differs from other ways of us ## What is Headless WordPress? -_Headless WordPress_ is the practice of using WordPress as a [headless CMS](/docs/how-to/sourcing-data/headless-cms/) for your [JAMstack](/docs/glossary/jamstack/) site. Headless WordPress takes advantage of the WordPress REST API to separate its content from the frontend that displays it. +A _headless WordPress_ site is one that uses WordPress for managing content and some other custom frontend stack to display that content. Headless WordPress enables content writers to use a familiar interface while giving web developers the flexibility to use any frontend technology stack. > Note: WordPress has two products: an open source, self-hosted package that you can [download](https://wordpress.org/) from WordPress.org; and a hosted service, [WordPress.com](https://wordpress.com/). This article applies to both. @@ -21,12 +21,12 @@ Gatsby [supports WordPress](/docs/how-to/sourcing-data/sourcing-from-wordpress/) npm install gatsby-source-wordpress ``` -The `gatsby-source-wordpress` plugin works with self-hosted WordPress sites, and those hosted by WordPress.com. Be aware, however, that the WordPress.com API supports a smaller set of features than that of self-hosted WordPress sites. It's also compatible with the [Advanced Custom Fields](https://www.advancedcustomfields.com/) plugin. +The `gatsby-source-wordpress` plugin works with self-hosted WordPress sites and those hosted by WordPress.com. Be aware, however, that the WordPress.com API supports a smaller set of features than that of self-hosted WordPress sites. -Headless WordPress lets your content team use an interface they're familiar with, while giving you the flexibility to use any frontend you'd like. +Headless WordPress enables content writers to use a familiar interface while giving web developers the flexibility to use any frontend technology stack. ## Learn More -- [REST API Resources](https://developer.wordpress.com/docs/api/) from WordPress.com -- [WordPress REST API](https://developer.wordpress.org/rest-api/) for self-hosted WordPress -- [How To Build A Blog with WordPress and Gatsby.js](/blog/2019-04-26-how-to-build-a-blog-with-wordpress-and-gatsby-part-1/) from the Gatsby blog +- [Gatsby's WordPress integration](/plugins/gatsby-source-wordpress/) for headless WordPress projects +- [GraphQL for WordPress](https://www.wpgraphql.com/) open-source plugin +- [Why Gatsby chose WordPress](/blog/gatsby-blog-wordpress/) - a case study diff --git a/docs/docs/glossary/npm.md b/docs/docs/glossary/npm.md index 5d6ab822e1b45..8a7a30512494e 100644 --- a/docs/docs/glossary/npm.md +++ b/docs/docs/glossary/npm.md @@ -13,7 +13,7 @@ update libraries and frameworks (dependencies) for Node-based projects, and interact with the npm Registry. You'll use npm to install and upgrade Gatsby and its plugins. -npm is a [command line](/docs/glossary#command-line) tool. You'll need Terminal (Mac, Linux) or Command Prompt (Windows) in order to run its commands. To use one of npm's features, type `npm ` . For example, `npm help` displays a list of available features, including `install`, `uninstall`, `update`, and `search`. +npm is a [command line](/docs/glossary#command-line) tool. You'll need Terminal (Mac, Linux) or Command Prompt (Windows) in order to run its commands. To use one of npm's features, type `npm `. For example, `npm help` displays a list of available features, including `install`, `uninstall`, `update`, and `search`. npm is installed alongside Node during the default [installation process](/docs/tutorial/part-zero/#install-nodejs-for-your-appropriate-operating-system). You don't need to take any additional steps to add it to your environment. diff --git a/docs/docs/how-to/adding-common-features/adding-search.md b/docs/docs/how-to/adding-common-features/adding-search.md index 7431f9b1003de..d45ca0c75e810 100644 --- a/docs/docs/how-to/adding-common-features/adding-search.md +++ b/docs/docs/how-to/adding-common-features/adding-search.md @@ -36,7 +36,7 @@ Another option is to use an external search engine. This solution is much more s There are many options available, including both self-hosted and commercially hosted open source: - [ElasticSearch](https://www.elastic.co/products/elasticsearch) — OSS and has commercial hosting available -- [Solr](http://lucene.apache.org/solr/) — OSS and has commercial hosting available +- [Solr](https://solr.apache.org) — OSS and has commercial hosting available - [Algolia](https://www.algolia.com/) — Commercial Of these, the most common solution is Algolia. The Gatsby docs include a guide to adding Algolia to your site: diff --git a/docs/docs/how-to/images-and-media/using-gatsby-plugin-image.md b/docs/docs/how-to/images-and-media/using-gatsby-plugin-image.md index 2e59d727e2327..4d5e8aec1d92a 100644 --- a/docs/docs/how-to/images-and-media/using-gatsby-plugin-image.md +++ b/docs/docs/how-to/images-and-media/using-gatsby-plugin-image.md @@ -1,29 +1,30 @@ --- -title: Using the beta Gatsby Image plugin +title: Using the Gatsby Image plugin --- +_If you're looking for a guide on using the deprecated `gatsby-image` package, it can be found in the [How to use Gatsby Image](/docs/how-to/images-and-media/using-gatsby-image) doc._ + Adding responsive images to your site while maintaining high performance scores can be difficult to do manually. The Gatsby Image plugin handles the hard parts of producing images in multiple sizes and formats for you! -Want to learn more about image optimization challenges? Read the Conceptual Guide: [Why Gatsby's Automatic Image Optimizations Matter](docs/conceptual/using-gatsby-image/). For full documentation on all configuration options, see [the reference guide](/docs/reference/built-in-components/gatsby-plugin-image). +Want to learn more about image optimization challenges? Read the Conceptual Guide: [Why Gatsby's Automatic Image Optimizations Matter](/docs/conceptual/using-gatsby-image/). For full documentation on all configuration options, see [the reference guide](/docs/reference/built-in-components/gatsby-plugin-image). The new Gatsby Image plugin is currently in beta, but you can try it out now and see what it can do for the performance of your site. ## Getting started -First you need to install the following packages: +1. Install the following packages: ```shell npm install gatsby-plugin-image gatsby-plugin-sharp gatsby-source-filesystem gatsby-transformer-sharp ``` -You then need to add the plugins to your `gatsby-config.js`: +2. Add the plugins to your `gatsby-config.js`: ```js:title=gatsby-config.js module.exports = { plugins: [ `gatsby-plugin-image`, `gatsby-plugin-sharp`, - `gatsby-source-filesystem`, `gatsby-transformer-sharp`, ], } @@ -31,6 +32,8 @@ module.exports = { If you already have some of these plugins installed, please check that they're updated to the latest version. +Note that `gatsby-source-filesystem` is not included in this config. If you are sourcing from your local filesystem to use `GatsbyImage` please configure accordingly. Otherwise, downloading the dependency without configuration is sufficient. + ## Using the Gatsby Image components @@ -199,4 +202,77 @@ If your site uses the old `gatsby-image` component, you can use a codemod to hel npx gatsby-codemods gatsby-plugin-image ``` -This will convert all GraphQL queries and components to use the new plugin. For more information see the full migration guide. +This will convert all GraphQL queries and components to use the new plugin. For more information see the full [migration guide](/docs/reference/release-notes/image-migration-guide/). + +## Troubleshooting + +If you're running into issues getting everything to work together we recommend following these steps. + +1. Are your dependencies installed? + +Check your package.json file for the following entries: + +- `gatsby-plugin-image` +- `gatsby-plugin-sharp` +- `gatsby-transformer-sharp` (If you're querying for dynamic images) +- `gatsby-source-filesystem` (If you're using the StaticImage component) + +If not, install them. + +2. Have you added the necessary information to your `gatsby-config.js` file? + +All of these plugins should be in your plugins array. Reminder that the `gatsby-image` package did not get included, so this is a change. + +- `gatsby-plugin-image` +- `gatsby-plugin-sharp` +- `gatsby-transformer-sharp` (If you're querying for dynamic images) + +If not, add them. + +3. Do your queries in GraphiQL return the data you expect? + +There are two paths here. + +If you're using StaticImage: + +Try running + +```graphql +query MyQuery { + allFile { + nodes { + relativePath + } + } +} +``` + +Do you see results with `.cache/caches/gatsby-plugin-image` in the path? + +If not, check steps 1 and 2 above. + +If you're using GatsbyImage: + +Run the query you're using in your site. Does it return a gatsbyImageData object? + +If not, check steps 1 and 2 above. + +4. Do the images render when you run your site? + +Do you see errors in your `gatsby develop` logs? Do you see errors in your browser console? + +For StaticImage: + +Inspect the element on your page. Does it include a `div` with `gatsby-image-wrapper`? How about an internal `source` element? + +If not, double check the component usage. Did you use `src`? Is the relative path correct? + +For GatsbyImage: + +Trying using `console.log` to check the the object you're passing as the `image` prop. Is it there? + +If not, make sure you're using the same object you saw return from your query. + +5. Are the images working yet? + +If you still see problems and think it's a bug, please [file an issue](https://github.com/gatsbyjs/gatsby/issues) and let us know how far in these steps you progressed. diff --git a/docs/docs/how-to/local-development/gatsby-on-linux.md b/docs/docs/how-to/local-development/gatsby-on-linux.md index 1b84651adbe9b..baa150d4f6e4f 100644 --- a/docs/docs/how-to/local-development/gatsby-on-linux.md +++ b/docs/docs/how-to/local-development/gatsby-on-linux.md @@ -79,7 +79,7 @@ Finally, install `git` which will be necessary for creating your first Gatsby pr sudo dnf install git ``` -## Archlinux and other `pacman` based distros +## Arch Linux and other `pacman` based distros Begin by updating. diff --git a/docs/docs/how-to/performance/improving-site-performance.md b/docs/docs/how-to/performance/improving-site-performance.md index 7674bd66cdfed..a8091de48dfc8 100644 --- a/docs/docs/how-to/performance/improving-site-performance.md +++ b/docs/docs/how-to/performance/improving-site-performance.md @@ -26,7 +26,7 @@ There are two options for this: - Gatsby Cloud has Lighthouse performance reports built into its CI/CD. Every time someone opens a pull request or merges into master, a Lighthouse report will be run and the performance score displayed. -- Use a third-party service that offers performance monitoring. Different services offer different options -- schedule runs on a daily basis or CI/CD integration through Github (or your source control service). +- Use a third-party service that offers performance monitoring. Different services offer different options -- schedule runs on a daily basis or CI/CD integration through GitHub (or your source control service). For additional precision, run Lighthouse multiple times and take the median result. @@ -48,7 +48,7 @@ Performance work can be surprisingly nonlinear in impact. When you run a test in your testing tool of choice, it will give you a number of recommendations. While this can feel like a laundry list of issues, it can be helpful to understand the five core categories that these issues are bucketed into. - Blocking calls & third-party scripts. -- Javascript bundle size. +- JavaScript bundle size. - Stylesheets and font files. - Images and other media. - Resource requests & CDN caching configuration. @@ -79,9 +79,9 @@ Other options include: - if you are using [html.js](https://www.gatsbyjs.org/docs/custom-html/) instead, you can modify that fileto include your snippet. -### Reduce your Javascript bundle cost +### Reduce your JavaScript bundle cost -Among all assets, Javascript can be uniquely costly to your performance. This is due to three main reasons: +Among all assets, JavaScript can be uniquely costly to your performance. This is due to three main reasons: - Like other assets, it needs to be loaded into your browser. @@ -139,7 +139,7 @@ We recommend you use the [gatsby plugin to install `loadable-components`](https: #### Step 6: Consider using the Preact plugin -[Preact](https://preactjs.com/) is a UI library that works similarly to React, but is much smaller (~3kb compressed as opposed to ~40kb). [Gatsby-plugin-preact](https://www.gatsbyjs.com/plugins/gatsby-plugin-preact/) is a drop-in plugin that will render your site in Preact instead of React, cutting 35-40kb of Javascript from your bundle. +[Preact](https://preactjs.com/) is a UI library that works similarly to React, but is much smaller (~3kb compressed as opposed to ~40kb). [Gatsby-plugin-preact](https://www.gatsbyjs.com/plugins/gatsby-plugin-preact/) is a drop-in plugin that will render your site in Preact instead of React, cutting 35-40kb of JavaScript from your bundle. This step can make sense if the `framework.js` bundle is a large part of your overall bundle size, and want to further optimize. diff --git a/docs/docs/how-to/previews-deploys-hosting/deploying-to-gatsby-cloud.md b/docs/docs/how-to/previews-deploys-hosting/deploying-to-gatsby-cloud.md index e931768884b7c..e354db21d61c7 100644 --- a/docs/docs/how-to/previews-deploys-hosting/deploying-to-gatsby-cloud.md +++ b/docs/docs/how-to/previews-deploys-hosting/deploying-to-gatsby-cloud.md @@ -6,12 +6,13 @@ This guide will walk you through building and deploying your Gatsby site on [Gat ## Why Use Gatsby Cloud -Gatsby Cloud is a platform of stable, trusted tools launched by the team behind Gatsby.js in late 2019 that enables web creators to build better websites. It offers unique features that remove friction in your team's workflow including: +Gatsby Cloud is a platform of stable, trusted tools launched by the team behind Gatsby in late 2019 that enables web creators to build better websites. It offers unique features that remove friction in your team's workflow including: - [**Quick Connect**](https://support.gatsbyjs.com/hc/en-us/articles/360061317133-Quick-Connect) that empowers new users to create projects in minutes with a Content Management System (CMS), sample content, and connected Gatsby starter. - [**Real-time Preview**](https://support.gatsbyjs.com/hc/en-us/articles/360055676874-CMS-Previews) to simplify content creation and collaboration. Preview offers a private playground for developers, designers, marketers, and content creators by providing a shareable temporary URL for viewing changes immediately and in context. With instant updates triggered by a CMS or webhooks, it’s a shareable, hot-reloading preview. - **Numerous CMS Integrations**, many of which are automatic - **Builds** is the fastest continuous deployment solution for Gatsby sites and apps- up to 20x faster build times compared to other solutions. Build with Gatsby and deploy to your favorite CDN. +- **Hosting** allows you to easily host your site and connect a domain with a free TLS certificate. - **Reports** provide automated Lighthouse performance checks and deploy previews to fix errors before they’re published. Best of all, Gatsby Cloud includes a [free tier](/pricing/) designed to comfortably support personal and small sites. @@ -35,11 +36,11 @@ If you want to work with a CMS without automatic integration support you still c - Drupal - Strapi -In addition, Gatsby Cloud offers a POST endpoint for manually integrating with CMSs that support webhooks. +In addition, Gatsby Cloud offers a `POST` endpoint for manually integrating with CMSs that support webhooks. ### Hosting Integrations -Gatsby Cloud offers automatic integration with the following hosting providers: +While Gatsby Cloud offers hosting, you can also configure automatic integration with the following 3rd party hosting providers: - Netlify - Amazon S3 @@ -115,21 +116,19 @@ Please refer to the [Gatsby Cloud Docs](https://support.gatsbyjs.com/hc/en-us/ar 11. If a build fails, you can click **View Details** to view the warning, errors, and raw logs for the build. -## Set up hosting for your site +## Set up Hosting for your site -1. Navigate to your site in your Gatsby Cloud [Dashboard](https://www.gatsbyjs.com/dashboard/sites). Under the _Site Settings_ tab, navigate to the _Integrations_ > _Hosting_ subsection. +1. Navigate to your site in your Gatsby Cloud [Dashboard](https://www.gatsbyjs.com/dashboard/sites). Under the _Site Settings_ tab, navigate to the _Hosting_ subsection. -2. To setup an integration, click **Connect** next to the hosting provider of your choice. +2. If your site has built, you can click on the url for `YOUR-SITE-NAME.gatsbyjs.io` to see it live! -3. Follow the prompts to authorize with your hosting provider. +3. You can also connect a custom domain by clicking the "Add Domain" button and following instructions there to set up your DNS records. - > The [Gatsby Cloud Docs](https://support.gatsbyjs.com/hc/en-us/sections/360012243573-Deploying-to-a-Hosting-Service) provide specific tutorials for each hosting provider. + > The [Gatsby Cloud Docs](https://support.gatsbyjs.com/hc/en-us/sections/360012243573-Deploying-to-a-Hosting-Service) provide specific instructions on how to connect your domain and add DNS records. -4. At this point your hosting integration should be setup. +4. Once the TLS certificate for your site has been generated, you will be able to see you site live on your own domain! - > You can verify this by returning to _Site Settings_ > _Integrations_ > _Hosting_ where your new integration should show as _Connected_ in green. - -5. Now when a build is triggered, your site will be deployed to your hosting target(s). +5. Now when a production build is triggered, your site will be deployed to your domains. ## Additional Resources diff --git a/docs/docs/how-to/styling/css-modules.md b/docs/docs/how-to/styling/css-modules.md index 4f2dc157e0b80..ea395d02a84a9 100644 --- a/docs/docs/how-to/styling/css-modules.md +++ b/docs/docs/how-to/styling/css-modules.md @@ -28,7 +28,7 @@ The CSS in a CSS module is no different than normal CSS, but the extension of th ```jsx:title=src/components/container.js import React from "react" // highlight-next-line -import containerStyles from "./container.module.css" +import * as containerStyles from "./container.module.css" export default function Container({ children }) { return ( @@ -48,7 +48,7 @@ Here's an example where the class name `container` is added to the DOM along wit ```jsx:title=src/components/container.js import React from "react" -import containerStyles from "./container.module.css" +import * as containerStyles from "./container.module.css" export default function Container({ children }) { return ( diff --git a/docs/docs/how-to/testing/unit-testing.md b/docs/docs/how-to/testing/unit-testing.md index 626573afeaa6a..68d1b97a6c6a6 100644 --- a/docs/docs/how-to/testing/unit-testing.md +++ b/docs/docs/how-to/testing/unit-testing.md @@ -242,6 +242,36 @@ const babelOptions = { Once this is changed, you can write your tests in TypeScript using the `.ts` or `.tsx` extensions. +### Using tsconfig paths + +If you are using [tsconfig paths](https://www.typescriptlang.org/tsconfig#paths) there is a single change to your config. + +1. Add [ts-jest](https://github.com/kulshekhar/ts-jest) + +```shell +npm install --save-dev ts-jest +``` + +2. Update `jest.config.js` to import and map `tsconfig.json` paths + +```js:title=jest.config.js +const { compilerOptions } = require("./tsconfig.json") +const { pathsToModuleNameMapper } = require("ts-jest/utils") +const paths = pathsToModuleNameMapper(compilerOptions.paths, { + prefix: "/", +}) +``` + +3. Add paths to `jest.config.js` moduleNameMapper + +```js:title=jest.config.js + moduleNameMapper: { + '.+\\.(css|styl|less|sass|scss)$': `identity-obj-proxy`, + '.+\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': `/tests/file-mock.js`, + ...paths, + }, +``` + ## Other resources If you need to make changes to your Babel config, you can edit the config in diff --git a/docs/docs/images-and-files.md b/docs/docs/images-and-files.md index e2f8d7622dd41..c3216a9274ad6 100644 --- a/docs/docs/images-and-files.md +++ b/docs/docs/images-and-files.md @@ -2,7 +2,7 @@ title: Images, Files & Video in Gatsby --- -Gatsby provides multiple solutions for adding images, video, and files to your projects. And a pro tip: you don't necessarily have to use GraphQL! From [imports](/docs/how-to/images-and-media/importing-assets-into-files/) and use of the [static folder](/docs/how-to/images-and-media/static-folder/) to dynamic queries with [Gatsby Image](/docs/how-to/images-and-media/using-gatsby-image/) to prevent image bloat, you've got options. +Gatsby provides multiple solutions for adding images, video, and files to your projects. And a pro tip: you don't necessarily have to use GraphQL! From [imports](/docs/how-to/images-and-media/importing-assets-into-files/) and use of the [static folder](/docs/how-to/images-and-media/static-folder/) to dynamic queries with [gatsby-plugin-image](/docs/how-to/images-and-media/using-gatsby-plugin-image/) to prevent image bloat, you've got options. This section will walk you through several common patterns for handling media with Gatsby, where you can learn about the pros and cons of each method. diff --git a/docs/docs/plugins.md b/docs/docs/plugins.md index 3770df857703f..6403d259b9d46 100644 --- a/docs/docs/plugins.md +++ b/docs/docs/plugins.md @@ -4,7 +4,7 @@ title: Plugins Gatsby plugins are Node.js packages that implement Gatsby APIs. For larger, more complex sites, plugins let you modularize your site customizations into site-specific plugins. -There are many types of Gatsby plugins, including [data sourcing](/plugins/?=gatsby-source), [SEO](/plugins/?=seo), [responsive images](/plugins/gatsby-image/?=gatsby-image), [offline support](/plugins/gatsby-plugin-offline/), [Sass support](/plugins/gatsby-plugin-sass/), [sitemaps](/plugins/gatsby-plugin-sitemap/), [RSS feeds](/plugins/gatsby-plugin-feed/), [TypeScript](/plugins/gatsby-plugin-typescript/), [Google Analytics](/plugins/gatsby-plugin-google-analytics/), and more. You can also [make your own plugins](/docs/creating-plugins/)! +There are many types of Gatsby plugins, including [data sourcing](/plugins/?=gatsby-source), [SEO](/plugins/?=seo), [responsive images](/plugins/gatsby-plugin-image/?=gatsby-plugin-image), [offline support](/plugins/gatsby-plugin-offline/), [Sass support](/plugins/gatsby-plugin-sass/), [sitemaps](/plugins/gatsby-plugin-sitemap/), [RSS feeds](/plugins/gatsby-plugin-feed/), [TypeScript](/plugins/gatsby-plugin-typescript/), [Google Analytics](/plugins/gatsby-plugin-google-analytics/), and more. You can also [make your own plugins](/docs/creating-plugins/)! Gatsby themes are a type of plugin that include a `gatsby-config.js` file and add **pre-configured** functionality, data sourcing, and/or UI code to Gatsby sites. To learn more about theme use cases and APIs, check out the [themes section of the docs](/docs/themes/). To learn about how plugins differ from themes and starters refer to the [Plugins, Themes, & Starters conceptual guide](/docs/conceptual/plugins-themes-and-starters/). diff --git a/docs/docs/porting-an-html-site-to-gatsby.md b/docs/docs/porting-an-html-site-to-gatsby.md index 8e252321aa6f3..9e929d933b3c6 100644 --- a/docs/docs/porting-an-html-site-to-gatsby.md +++ b/docs/docs/porting-an-html-site-to-gatsby.md @@ -560,7 +560,7 @@ website-domain ## Next steps -Gatsby can handle images through direct imports to page and component files too! The [asset import documentation](/docs/how-to/images-and-media/importing-assets-into-files/) covers this. There is also the [Gatsby Image](/docs/reference/built-in-components/gatsby-image/) component for even deeper optimizations. Once assets are handled through Gatsby, plugins can be used to optimize their processing and delivery. +Gatsby can handle images through direct imports to page and component files too! The [asset import documentation](/docs/how-to/images-and-media/importing-assets-into-files/) covers this. There is also [gatsby-plugin-image](/docs/how-to/images-and-media/using-gatsby-plugin-image) component for even deeper optimizations. Once assets are handled through Gatsby, plugins can be used to optimize their processing and delivery. The [building with components doc](/docs/conceptual/building-with-components/) has information about why Gatsby uses React component architecture and how it fits into a Gatsby application. diff --git a/docs/docs/porting-from-create-react-app-to-gatsby.md b/docs/docs/porting-from-create-react-app-to-gatsby.md index 73d1cefde9129..b3bf33a4e1cf7 100644 --- a/docs/docs/porting-from-create-react-app-to-gatsby.md +++ b/docs/docs/porting-from-create-react-app-to-gatsby.md @@ -19,7 +19,7 @@ _Both_ Create React App and Gatsby use React and allow users to build apps more Gatsby enables some useful performance optimizations for you, by default. Route-based code splitting and pre-loading of the _next_ resources make your application lightning fast, without any additional effort! Further still, the following optimizations and techniques are also available to you: - `gatsby-link` uses an [intersection observer to preload linked pages](/blog/2019-04-02-behind-the-scenes-what-makes-gatsby-great/#intersectionobserver) when they appear in the viewport, making them feel like they load _instantly_ -- `gatsby-image` will create optimized versions of your images in different sizes, loading a smaller, optimized version of an image and replacing it with a higher resolution version when loading has finished. It also uses an intersection observer to cheaply lazy load images. Check out [the demo](https://using-gatsby-image.gatsbyjs.org/) to see for yourself +- `gatsby-plugin-image` will create optimized versions of your images in different sizes, loading a smaller, optimized version of an image and replacing it with a higher resolution version when loading has finished. It also uses an intersection observer to cheaply lazy load images. Check out [the demo](https://using-gatsby-image.gatsbyjs.org/) to see for yourself These features and more work together to make your Gatsby site fast by default. If you'd like a deep dive on these and other performance optimizations, check out [this blog post](/blog/2019-04-02-behind-the-scenes-what-makes-gatsby-great/) diff --git a/docs/docs/processing-payments-with-square.md b/docs/docs/processing-payments-with-square.md index a0e6ec83dece7..34a0550bccf21 100644 --- a/docs/docs/processing-payments-with-square.md +++ b/docs/docs/processing-payments-with-square.md @@ -91,6 +91,99 @@ const IndexPage = () => { export default IndexPage ``` +To charge payment source using nonce, a server-side implementation is required which will uses the Square Node.js SDK library to call the Square Payments API. + +In the `PaymentForm` component, call `processPayment` end point once the nonce is generated. Use the nonce, amount and currency to capture payment. API can be served using netlify lambda function, but any form backend implementation will work. + +```js +axios + .post("PROCESS_PAYMENT_API_END_POINT", { + amount: 1 * 100 // charge 1 USD, + currency: "USD", + nonce, //highlight-line + }) + .then((result) => { + alert('Payment complete successfully!\nCheck browser developer console for more details'); + }) + .catch((error) => { + console.log(`error in processing payment:${error}`); + alert('Payment failed to complete!\nCheck browser developer console for more details'); + this.setState({ error: true }); + }); +``` + +Below is the Netlify lambda implementation. Create a PaymentsApi object and call the CreatePayment endpoint to charge the payment source. After receiving the `Payments.CreatePayment` endpoint request, Square processes the payment and returns a response. + +```js +import crypto from "crypto" +import { ApiClient, PaymentsApi } from "square-connect" + +const headers = { + "Access-Control-Allow-Origin": "*", + "Access-Control-Allow-Headers": + "Origin, X-Requested-With, Content-Type, Accept", +} + +exports.handler = async (event, context) => { + try { + // Set the Access Token (while testing use the sandbox one) + const accessToken = "YOUR_ACCESS_TOKEN" + + // retrieves the payment data sent from the website + const data = JSON.parse(event.body) + + // Set Square Connect credentials and environment + const defaultClient = ApiClient.instance + + // Configure OAuth2 access token for authorization: oauth2 + const oauth2 = defaultClient.authentications["oauth2"] + oauth2.accessToken = accessToken + + // Set 'basePath' to switch between sandbox env and production env + // sandbox: https://connect.squareupsandbox.com + // production: https://connect.squareup.com + defaultClient.basePath = "https://connect.squareupsandbox.com" + + // generate a idempotency key for the payment + // length of idempotency_key should be less than 45 + const idempotency_key = crypto.randomBytes(22).toString("hex") + + // instantiate the api + const payments_api = new PaymentsApi() + + // request object to process the payment + const request_body = { + source_id: data.nonce, + amount_money: { + amount: data.amount, + currency: data.currency, + }, + idempotency_key: idempotency_key, + } + + // calls the square payments api to process the payment issued + const response = await payments_api.createPayment(request_body) + return { + statusCode: 200, + headers, + body: JSON.stringify({ + message: `Payment Successful`, + paymentInfo: response, + }), + } + } catch (error) { + console.log(error) + return { + statusCode: 500, + headers, + body: "Something went wrong. Try again later", + } + } +} +``` + +Review the payment in the Sandbox Seller Dashboard. The payment is credited to the Sandbox test account whose access token is used in the application. + ## The Square sandbox You can test your setup [using the Square sandbox](https://developer.squareup.com/docs/how-to/testing/sandbox). To do so, you'll need to return to your [developer dashboard](https://developer.squareup.com/apps). In the "Credentials" tab, you can toggle back and forth between your production and sandbox credentials! @@ -99,5 +192,7 @@ You can test your setup [using the Square sandbox](https://developer.squareup.co - [`SqPaymentForm` documentation](https://developer.squareup.com/docs/api/paymentform#navsection-paymentform) - [Square's tutorial for online payment options](https://developer.squareup.com/docs/online-payment-options) +- [Sqaure's Payment Walkthrough](https://developer.squareup.com/docs/payment-form/payment-form-walkthrough) +- [Square's Test Cards](https://developer.squareup.com/docs/testing/test-values) - Square's blog post on [Online Payments with React + Square](https://developer.squareup.com/blog/online-payments-form-react/) - Example code for [using Square Payments](https://github.com/gatsbyjs/gatsby/tree/master/examples/using-square-payments) diff --git a/docs/docs/recipes/styling-css.md b/docs/docs/recipes/styling-css.md index f3574515acc88..fe85da56bbf06 100644 --- a/docs/docs/recipes/styling-css.md +++ b/docs/docs/recipes/styling-css.md @@ -194,7 +194,7 @@ export default function UsersList() { import React from "react" // highlight-start -import style from "./index.module.css" +import * as style from "./index.module.css" export default function Home() { return ( diff --git a/docs/docs/reference/built-in-components/gatsby-image.md b/docs/docs/reference/built-in-components/gatsby-image.md index d53ce8d3ac75d..4bd4afb3982e8 100644 --- a/docs/docs/reference/built-in-components/gatsby-image.md +++ b/docs/docs/reference/built-in-components/gatsby-image.md @@ -2,6 +2,8 @@ title: Gatsby Image API --- +_This document talks about the deprecated image plugin. Please check out how to work with the new [gatsby-plugin-image](/docs/how-to/images-and-media/using-gatsby-plugin-image)_ + Part of what makes Gatsby sites so fast is its recommended approach to handling images. `gatsby-image` is a React component designed to work seamlessly with Gatsby’s [native image processing](https://image-processing.gatsbyjs.org/) capabilities powered by GraphQL and [gatsby-plugin-sharp](/plugins/gatsby-plugin-sharp/) to easily and completely optimize image loading for your sites. > _Note: gatsby-image is **not** a drop-in replacement for ``. It’s optimized for responsive fixed width/height images and images that stretch the full-width of a container. There are also other ways to [work with images](/docs/images-and-files/) in Gatsby that don't require GraphQL._ diff --git a/docs/docs/reference/built-in-components/gatsby-plugin-image.md b/docs/docs/reference/built-in-components/gatsby-plugin-image.md index c5daa53f4db99..1c02da7e1f43d 100644 --- a/docs/docs/reference/built-in-components/gatsby-plugin-image.md +++ b/docs/docs/reference/built-in-components/gatsby-plugin-image.md @@ -242,7 +242,7 @@ The Gatsby Image plugin uses [sharp](https://sharp.pixelplumbing.org) for image ## Helper functions -There are a number of utility functions to help you work with `gatsbyImageData` objects. We stringly recommend that you do not try to access the internals of these objects directly, as the format could change. +There are a number of utility functions to help you work with `gatsbyImageData` objects. We strongly recommend that you do not try to access the internals of these objects directly, as the format could change. ### `getImage` diff --git a/docs/docs/reference/built-in-components/layouts.mp4 b/docs/docs/reference/built-in-components/layouts.mp4 index a85a57fa5a77d..2ff6fdef5d268 100644 Binary files a/docs/docs/reference/built-in-components/layouts.mp4 and b/docs/docs/reference/built-in-components/layouts.mp4 differ diff --git a/docs/docs/reference/release-notes/image-migration-guide.md b/docs/docs/reference/release-notes/image-migration-guide.md index e6f3b510b1acf..afad1c9f55c09 100644 --- a/docs/docs/reference/release-notes/image-migration-guide.md +++ b/docs/docs/reference/release-notes/image-migration-guide.md @@ -118,7 +118,7 @@ Due to the changes to `gatsby-plugin-image`, there is some functionality that is 1. `GatsbyImage` is no longer a class component and therefore cannot be extended. You can use [composition](https://reactjs.org/docs/composition-vs-inheritance.html) instead. 2. `fluid` images no longer exist, and the `fullWidth` replacement does not take `maxWidth` or `maxHeight`. -3. Art direction is no longer supported. +3. The art direction API has changed, see the [`gatsby-plugin-image` reference guide](/docs/reference/built-in-components/gatsby-plugin-image#withartdirection) for specifics. 4. The component no longer takes a decomposed object, and the following code is not valid. You should avoid accessing or changing the contents of the `gatsbyImageData` object, as it is not considered to be a public API, so can be changed without notice. ```javascript diff --git a/docs/docs/reference/release-notes/migrating-from-v1-to-v2.md b/docs/docs/reference/release-notes/migrating-from-v1-to-v2.md index 4ce2f09f4493a..eab564e6fc6f1 100644 --- a/docs/docs/reference/release-notes/migrating-from-v1-to-v2.md +++ b/docs/docs/reference/release-notes/migrating-from-v1-to-v2.md @@ -682,7 +682,7 @@ Here's an example with a class named `.my-class-name`: ```diff import React from "react" -import myStyles from "./my.module.css" +import * as myStyles from "./my.module.css" export default function Component({ children }) ( -
diff --git a/docs/docs/reference/release-notes/migrating-from-v2-to-v3.md b/docs/docs/reference/release-notes/migrating-from-v2-to-v3.md new file mode 100644 index 0000000000000..19cba9b7a2455 --- /dev/null +++ b/docs/docs/reference/release-notes/migrating-from-v2-to-v3.md @@ -0,0 +1,904 @@ +--- +title: Migrating from v2 to v3 +--- + +Looking for the [v2 docs](https://v2.gatsbyjs.com)? + +> Have you run into something that's not covered here? [Add your changes to GitHub!](https://github.com/gatsbyjs/gatsby/tree/master/docs/docs/reference/release-notes/migrating-from-v2-to-v3.md) + +## Introduction + +This is a reference for upgrading your site from Gatsby v2 to Gatsby v3. Since the last major release was in September 2018, Gatsby v3 includes a couple of breaking changes. If you're curious what's new, head over to the [v3.0 release notes](/docs/reference/release-notes/v3.0). + +> If you want to start fresh, run `npm init gatsby` or `yarn create gatsby` in your terminal. + +## Table of Contents + +- [Updating Your Dependencies](#updating-your-dependencies) +- [Handling Breaking Changes](#handling-breaking-changes) +- [Future Breaking Changes](#future-breaking-changes) +- [For Plugin Maintainers](#for-plugin-maintainers) +- [Known Issues](#known-issues) + +## Updating Your Dependencies + +First, you need to update your dependencies. + +### Update Gatsby version + +You need to update your `package.json` to use the latest version of Gatsby. + +```json:title=package.json +{ + "dependencies": { + "gatsby": "^3.0.0" + } +} +``` + +Or run + +```shell +npm install gatsby@latest +``` + +**Please note:** If you use **npm 7** you'll want to use the `--legacy-peer-deps` option when following the instructions in this guide. For example, the above command would be: + +```shell +npm install gatsby@latest --legacy-peer-deps +``` + +### Update Gatsby related packages + +Update your `package.json` to use the latest version of Gatsby related packages. You should upgrade any package name that starts with `gatsby-*`. Note, this only applies to plugins managed in the [gatsbyjs/gatsby](https://github.com/gatsbyjs/gatsby) repository. If you're using community plugins, they might not be upgraded yet. Many plugins won't need updating so they may keep working (if not, please check their repository for the current status). You can run an npm script to see all outdated dependencies. + +#### npm + +```shell +npm outdated +``` + +Compare the "Wanted" and "Latest" versions and update their versions accordingly. For example, if you have this outdated version: + +```shell +> npm outdated + +Package Current Wanted Latest Location +gatsby-plugin-sharp 2.14.1 2.14.1 3.0.0 test +``` + +Install the new package with: + +```shell +npm install gatsby-plugin-sharp@latest +``` + +#### yarn + +```shell +yarn upgrade-interactive --latest +``` + +You'll be given an overview of packages where you can select to upgrade them to `latest`. + +#### Updating community plugins + +Using community plugins, you might see warnings like these in your terminal: + +```shell +warning Plugin gatsby-plugin-acme is not compatible with your gatsby version 3.0.0 - It requires gatsby@^2.32.0 +``` + +If you are using npm 7, the warning may instead be an error: + +```shell +npm ERR! ERESOLVE unable to resolve dependency tree +``` + +This is because the plugin needs to set its `peerDependencies` to the new version of Gatsby (see section [for plugin maintainers](#for-plugin-maintainers)). While this might indicate that the plugin has incompatibilities, in most cases they should continue to work. When using npm 7, you can pass the `--legacy-peer-deps` to ignore the warning and install anyway. Please look for already opened issues or PRs on the plugin's repository to see the status. If you don't see any, help the maintainers by opening an issue or PR yourself! :) + +#### Handling dependencies for plugins that are not yet updated + +If you run into the scenarios listed below, you will need to use yarn resolutions until the plugin authors upgrade the plugins they maintain. + +Gatsby has an _amazing_ ecosystem of plugins that make it easier to get up and running, and to incorporate various data sources and functionality into your Gatsby project. Part of that huge ecosystem includes dependency trees! + +Depending on how the plugin authors have declared dependencies (e.g. marking a package as a dependency instead of a peerDependency) within those plugins, there could be a myriad of failures that arise. If you encounter any of these issues when migrating your project to Gatsby Version 3, we recommend that you use [Yarn resolutions](https://yarnpkg.com/configuration/manifest#resolutions) within your `package.json`. + +**Please note:** If your rely on a plugin that is not found within the [list of plugins within the Gatsby framework](https://github.com/gatsbyjs/gatsby/tree/master/packages), you very well may need to use the following resolutions in the near term. + +The specific resolutions we recommend at this time are found below: + +```json:title=package.json +{ + "resolutions": { + "graphql": "^15.4.0", + "graphql-compose": "^7.25.0", + "webpack": "^5.24.2" + } +} +``` + +### Handling version mismatches + +When upgrading an already existing project (that has an existing `node_modules` folder and `package-lock.json` file) you might run into version mismatches for your packages as npm/yarn don't resolve to the latest/correct version. An example would be a version mismatch of `webpack@4` and `webpack@5` that can throw an error like this: + +```shell +Error: NormalModuleFactory.afterResolve (ReactRefreshPlugin) is no longer a waterfall hook, but a bailing hook instead. +``` + +An effective way to get around this issue is deleting `node_modules` and `package-lock.json` and then running `npm install` again. Alternatively, you can use `npm dedupe`. + +## Handling Breaking Changes + +This section explains breaking changes that were made for Gatsby v3. Most, if not all, of those changes had a deprecation message in v2. In order to successfully update, you'll need to resolve these changes. + +### Minimal Node.js version 12.13.0 + +We are dropping support for Node 10 as it is approaching maintenance EOL date (2021-04-30). +The new required version of Node is `12.13.0`. See the main changes in [Node 12 release notes](https://nodejs.org/en/blog/release/v12.0.0/). + +Check [Node’s releases document](https://github.com/nodejs/Release#nodejs-release-working-group) for version statuses. + +### webpack upgraded from version 4 to version 5 + +We tried our best to mitigate as much of the breaking change as we could. Some are sadly inevitable. We suggest looking at the [official webpack 5 blog post](https://webpack.js.org/blog/2020-10-10-webpack-5-release/) to get a comprehensive list of what changed. + +If you hit any problems along the way, make sure the Gatsby plugin or webpack plugin supports version 5. + +### ESLint upgraded from version 6 to version 7 + +If you're using Gatsby's default ESLint rules (no custom `eslintrc` file), you shouldn't notice any issues. If you do have a custom ESLint config, make sure to read the [ESLint 6 to 7 migration guide](https://eslint.org/docs/user-guide/migrating-to-7.0.0) + +### Gatsby's `Link` component + +The APIs `push`, `replace` & `navigateTo` in `gatsby-link` (an internal package) were deprecated in v2 and now with v3 completely removed. Please use `navigate` instead. + +```diff +import React from "react" +- import { navigateTo, push, replace } from "gatsby" ++ import { navigate } from "gatsby" + +const Form = () => ( +
{ + event.preventDefault() + +- navigateTo("/form-submitted/") // or push() or replace() ++ navigate("/form-submitted/") + }} + > +) +``` + +### Removal of `__experimentalThemes` + +The deprecated `__experimentalThemes` key inside `gatsby-config.js` was removed. You'll need to define your Gatsby themes inside the `plugins` array instead. + +```diff:title=gatsby-config.js +module.exports = { +- __experimentalThemes: ["gatsby-theme-blog"] ++ plugins: ["gatsby-theme-blog"] +} +``` + +### Removal of `pathContext` + +The deprecated API `pathContext` was removed. You need to rename instances of it to `pageContext`. For example, if you passed information inside your `gatsby-node.js` and accessed it in your page: + +```diff:title=src/templates/context.jsx +import React from "react" + +- const ContextPage = ({ pathContext }) => ( ++ const ContextPage = ({ pageContext }) => ( +
+

Hello from a page that uses the old pathContext

+

It was deprecated in favor of pageContext

+-

{pathContext.foo}

++

{pageContext.foo}

+
+) + +export default ContextPage +``` + +### Removal of `boundActionCreators` + +The deprecated API `boundActionCreators` was removed. Please rename its instances to `actions` to keep the same behavior. For example, in your `gatsby-node.js` file: + +```diff:title=gatsby-node.js +exports.createPages = (gatsbyArgs, pluginArgs) => { +- const { boundActionCreators } = gatsbyArgs ++ const { actions } = gatsbyArgs +} +``` + +### Removal of `deleteNodes` + +The deprecated API `deleteNodes` was removed. Please iterate over the `nodes` instead and call `deleteNode`: + +```diff +const nodes = ["an-array-of-nodes"] +- deleteNodes(nodes) ++ nodes.forEach(node => deleteNode(node)) +``` + +### Removal of `fieldName` & `fieldValue` from `createNodeField` + +The arguments `fieldName` and `fieldValue` were removed from the `createNodeField` API. Please use `name` and `value` instead. + +```diff:title=gatsby-node.js +exports.onCreateNode = ({ node, actions }) => { + const { createNodeField } = actions + + createNodeField({ + node, +- fieldName: "slug", +- fieldValue: "my-custom-slug", ++ name: "slug", ++ value: "my-custom-slug", + }) +} +``` + +### Removal of `hasNodeChanged` from public API surface + +This API is no longer necessary, as there is an internal check for whether or not a node has changed. + +### Removal of `sizes` & `resolutions` for image queries + +The `sizes` and `resolutions` queries were deprecated in v2 in favor of `fluid` and `fixed`. + +While `fluid`, `fixed`, and `gatsby-image` will continue to work in v3, we highly recommend migrating to the new `gatsby-plugin-image`. Read the [Migrating from `gatsby-image` to `gatsby-plugin-image`](/docs/reference/release-notes/image-migration-guide/) guide to learn more about its benefits and how to use it. + +```diff +import React from "react" +import { graphql } from "gatsby" +import Img from "gatsby-image" + +const Example = ({ data }) => { +
+- +- ++ ++ +
+} + +export default Example + +export const pageQuery = graphql` + query IndexQuery { + foo: file(relativePath: { regex: "/foo.jpg/" }) { + childImageSharp { +- sizes(maxWidth: 700) { +- ...GatsbyImageSharpSizes_tracedSVG ++ fluid(maxWidth: 700) { ++ ...GatsbyImageSharpFluid_tracedSVG + } + } + } + bar: file(relativePath: { regex: "/bar.jpg/" }) { + childImageSharp { +- resolutions(width: 500) { +- ...GatsbyImageSharpResolutions_withWebp ++ fixed(width: 500) { ++ ...GatsbyImageSharpFixed_withWebp + } + } + } + } +` +``` + +### Calling `touchNode` with the node id + +Calling `touchNode` with a string (the node id) was deprecated in Gatsby v2. Pass the full `node` to `touchNode` now. + +```diff:title=gatsby-node.js +exports.sourceNodes = ({ actions, getNodesByType }) => { + const { touchNode } = actions + +- getNodesByType("YourSourceType").forEach(node => touchNode(node.id)) ++ getNodesByType("YourSourceType").forEach(node => touchNode(node)) +} +``` + +### Calling `deleteNode` with the node id + +Calling `deleteNode` with a string (the node id) was deprecated in Gatsby v2. Pass the full `node` to `deleteNode` now. + +```diff:title=gatsby-node.js +exports.onCreateNode = ({ actions, node }) => { + const { deleteNode } = actions + +- deleteNode(node.id) ++ deleteNode(node) +} +``` + +### Removal of three `gatsby-browser` APIs + +A couple of `gatsby-browser` APIs were removed. In the list below you can find the old APIs and their replacements: + +- `getResourcesForPathnameSync` => `loadPageSync` +- `getResourcesForPathname` => `loadPage` +- `replaceComponentRenderer` => `wrapPageElement` + +### Using a global `graphql` tag for queries + +Until now you were able to use the `graphql` tag for queries without explicitly importing it from Gatsby. You now have to import it: `import { graphql } from 'gatsby'` + +```diff:title=src/pages/index.js +import React from "react" ++ import { graphql } from "gatsby" + +const Page = ({ data }) => ( +
Show my data: {JSON.stringify(data, null, 2)}
+) + +export default Page + +export const query = graphql` + { + site { + siteMetadata { + description + } + } + } +` +``` + +### CSS Modules are imported as ES Modules + +The web moves forward and so do we. ES Modules allow us to better treeshake and generate smaller files. From now on you'll need to import cssModules as: `import { box } from './mystyles.module.css'` + +```diff:title=src/components/Box.js +import React from "react" +- import styles from './mystyles.module.css' ++ import { box } from './mystyles.module.css' + +const Box = ({ children }) => ( +-
{children}
++
{children}
+) + +export default Box +``` + +You can also still import all styles using the `import * as styles` syntax e.g. `import * as styles from './mystyles.module.css'`. However, this won't allow webpack to treeshake your styles so we discourage you from using this syntax. + +### File assets (fonts, pdfs, ...) are imported as ES Modules + +Assets are handled as ES Modules. Make sure to switch your require functions into imports. + +```diff:title=src/components/Layout.js +import React from "react" +import { Helmet } from "react-helmet"; ++ import myFont from '../assets/fonts/myfont.woff2' + +const Layout = ({ children }) => ( +
+ +- ++ + + {children} +
+) + +export default Layout +``` + +If you're using `require with expression` or `require.context` (which is not recommended), you'll have to append `.default` to your require statement to make it work. + +```diff:title=src/components/Layout.js +import React from "react" +import { Helmet } from "react-helmet"; + +const Layout = ({ children, font }) => ( +
+ +- ++ + {children} +
+) + +export default Layout +``` + +### webpack 5 node configuration changed (node.fs, node.path, ...) + +Some components need you to patch/disable node APIs in the browser, like `path` or `fs`. webpack removed these automatic polyfills. You now have to manually set them in your configurations: + +```diff:title=gatsby-node.js +exports.onCreateWebpackConfig = ({ actions }) => { + actions.setWebpackConfig({ +- node: { +- fs: "empty", +- path: "mock", +- }, ++ resolve: { ++ alias: { ++ path: require.resolve("path-browserify") ++ }, ++ fallback: { ++ fs: false, ++ } ++ } + }) +} +``` + +If it's still not resolved, the error message should guide you on what else you need to add to your webpack config. + +#### process is not defined + +A common error is `process is not defined`. webpack 4 polyfilled process automatically in the browser, but with v5 it's not the case anymore. + +If you're using `process.browser` in your components, you should switch to a window is not undefined check. + +```diff:title=src/components/Box.js +import React from "react" + +const Base64 = ({ text }) => { + let base64; +- if (process.browser) { ++ if (typeof window !== "undefined") { + base64 = btoa(text) + } else { + base64 = Buffer.from(text).toString('base64') + } + + return ( +
+ {base64} +
+ ) +} + +export default Base64 +``` + +If you're using any other process properties, you want to polyfill process. + +1. Install `process` library - `npm install process` +2. Configure webpack to use the process polyfill. + +```diff:title=gatby-node.js +exports.onCreateWebpackConfig = ({ actions, stage, plugins }) => { + if (stage === 'build-javascript' || stage === 'develop') { + actions.setWebpackConfig({ + plugins: [ + plugins.provide({ process: 'process/browser' }) + ] + }) + } +} +``` + +### GraphQL: character escape sequences in `regex` filter + +In v2, backslashes in `regex` filters of GraphQL queries had to be escaped +_twice_, so `/\w+/` needed to be written as `"/\\\\w+/"`. + +In v3, you only need to escape once: + +```diff:title=src/pages/index.js +const query = { + allFile( + filter: { +- relativePath: { regex: "/\\\\.png/" } ++ relativePath: { regex: "/\\.png/" } + } + ) { + nodes { + relativePath + } + } +} +``` + +### GraphQL: `__typename` field is no longer added automatically + +In v2, the `__typename` field used to be added implicitly when querying for a field of abstract type (interface or union). +In v3, `__typename` has to be added explicitly in your query: + +```diff:title=src/pages/index.js +import React from "react" +import { graphql } from "gatsby" + +const Page = ({ data }) => { + if (data.foo.someUnion.__typename === `A`) { + return data.foo.someUnion.a + } + if (data.foo.someUnion.__typename === `B`) { + return data.foo.someUnion.b + } + return null +} + +export default Page + +export const query = graphql` + { + foo { + someUnion { ++ __typename + ... on A { a } + ... on B { b } + } + } + } +` +``` + +### Schema Customization: Add explicit `childOf` extension to types with disabled inference + +Imagine you have node type `Foo` that has several child nodes of type `Bar` (so you expect field `Foo.childBar` to exist). +In Gatsby v2 this field was added automatically even if inference was disabled for type `Foo`. + +In Gatsby v3 you must declare a parent-child relationship explicitly for this case: + +```diff:title=gatsby-node.js +exports.createSchemaCustomization = ({ actions }) => { + const { createTypes } = actions + createTypes(` + type Foo implemenst Node @dontInfer { + id: ID! + } +- type Bar implements Node { ++ type Bar implements Node @childOf(types: ["Foo"]) { + id: ID! + } + `) +} +``` + +To make upgrading easier, check the CLI output of your site on the latest v2 and follow the suggestions +when you see a warning like this: + +```shell +warning Deprecation warning: In Gatsby v3 fields `Foo.childBar` and `Foo.childrenBar` +will not be added automatically because type `Bar` does not explicitly list type `Foo` +in `childOf` extension. + +Add the following type definition to fix this: + + type Bar implements Node @childOf(types: ["Foo"]) { + id: ID! + } + +https://www.gatsbyjs.com/docs/actions/#createTypes +``` + +If you don't see any warnings, you are safe to upgrade to v3. + +If this warning is displayed for a type defined by some plugin, open an issue in the plugin repo +with a suggestion to upgrade (and a link to this guide). + +You can still fix those warnings temporarily in your site's `gatsby-node.js` file until it is fixed in the plugin. + +Related docs: + +- [childOf directive](/docs/reference/graphql-data-layer/schema-customization/#defining-child-relations) +- [child/parent fields](/docs/schema-inference/#childparent-fields) +- [schema generation](/docs/schema-generation/#4-parent--children-relationships) + +### Schema Customization: Extensions must be set explicitly + +Starting with v3, whenever you define a field of complex type, you must also assign +the corresponding extension (or a custom resolver): + +```diff:title=gatsby-node.js +exports.createSchemaCustomization = ({ actions }) => { + const { createTypes } = actions + createTypes(` + type MyType { +- date: Date ++ date: Date @dateformat +- image: File ++ image: File @fileByRelativePath +- authorByEmail: Author ++ authorByEmail: Author @link + } + `) +} +``` + +In Gatsby v2, we add those extensions for you automatically but display a deprecation warning. + +To make upgrading easier, when you see a warning like the one below, check the CLI output of your site on the latest v2 and follow the suggestions provided. + +```shell +warning Deprecation warning: adding inferred extension `link` for field Foo.bar +In Gatsby v3, only fields with an explicit directive/extension will be resolved correctly. +Add the following type definition to fix this: + + type Foo implements Node { + bar: [Bar] @link(by: "id", from: "bar___NODE") + } + +https://www.gatsbyjs.com/docs/actions/#createTypes +``` + +If this warning is displayed for a type defined by some plugin, open an issue in the plugin repo +with a suggestion to upgrade (and a link to this guide). + +You can still fix those warnings temporarily in your site's `gatsby-node.js` until it is fixed in the plugin. + +If you don't see any warnings, you are safe to upgrade to v3. Read more about custom extensions in [this blog post](/blog/2019-05-17-improvements-to-schema-customization/). + +### Schema Customization: Removed `noDefaultResolvers` argument from inference directives + +Search for `noDefaultResolvers` entries and remove them: + +```diff:title=gatsby-node.js +exports.createSchemaCustomization = ({ actions }) => { + const { createTypes } = actions + createTypes(` +- type Foo implements Node @infer(noDefaultResolvers: true) ++ type Foo implements Node @infer + { + id: ID! + } + +- type Bar implements Node @dontInfer(noDefaultResolvers: true) ++ type Foo implements Node @dontInfer + { + id: ID! + } + + `) +} +``` + +[Deprecation announcement for `noDefaultResolvers`](/blog/2019-05-17-improvements-to-schema-customization/#-nodefaultresolvers-and-inference-modes). + +### Schema Customization: Remove `many` argument from `childOf` directive + +The `many` argument is no longer needed for the `childOf` directive in Gatsby v3: + +```diff:title=gatsby-node.js +exports.createSchemaCustomization = ({ actions }) => { + const { createTypes } = actions + createTypes(` +- type Foo implements Node @childOf(types: ["Bar"], many: true) ++ type Foo implements Node @childOf(types: ["Bar"]) + { + id: ID! + } + `) +} +``` + +### Schema Customization: Consistent return for `nodeModel.runQuery` + +For Gatsby v2, `nodeModel.runQuery` with `firstOnly: false` returns `null` when nothing is found. +In v3 it returns an empty array instead. + +To upgrade, find all occurrences of `runQuery` (with `firstOnly: false` or not set) and make sure checks for emptiness +are correct: + +```diff:title=gatsby-node.js +exports.createResolvers = ({ createResolvers }) => { + const resolvers = { + Foo: { + bars: { + resolve(source, args, context, info) { + const result = context.nodeModel.runQuery({ + query: {/* */}, + type: "Bar", + firstOnly: false, + }) +- if (result === null) { ++ if (result.length === 0) { + throw new Error("Not found!") + } + return result + }, + }, + }, + } + createResolvers(resolvers) +} +``` + +**Note:** When using argument `firstOnly: true` the returned value is `object` or `null`. +So do not confuse those two cases. + +## Future Breaking Changes + +This section explains deprecations that were made for Gatsby v3. These old behaviors will be removed in v4, at which point they will no longer work. For now, you can still use the old behaviors in v3, but we recommend updating to the new signatures to make future updates easier. + +### `touchNode` + +For Gatsby v2 the `touchNode` API accepted `nodeId` as a named argument. This now has been deprecated in favor of passing the full `node` to the function. + +```diff:title=gatsby-node.js +exports.sourceNodes = ({ actions, getNodesByType }) => { + const { touchNode } = actions + +- getNodesByType("YourSourceType").forEach(node => touchNode({ nodeId: node.id })) ++ getNodesByType("YourSourceType").forEach(node => touchNode(node)) +} +``` + +In case you only have an ID at hand (e.g. getting it from cache or as `__NODE`), you can use the `getNode()` API: + +```js:title=gatsby-node.js +exports.sourceNodes = async ({ actions, getNodesByType, cache }) => { + const { touchNode, getNode } = actions + const myNodeId = await cache.get("some-key") + + touchNode(getNode(myNodeId)) +} +``` + +### `deleteNode` + +For Gatsby v2, the `deleteNode` API accepted `node` as a named argument. This now has been deprecated in favor of passing the full `node` to the function. + +```diff:title=gatsby-node.js +exports.onCreateNode = ({ actions, node }) => { + const { deleteNode } = actions + +- deleteNode({ node }) ++ deleteNode(node) +} +``` + +### `@nodeInterface` + +For Gatsby v2, `@nodeInterface` was the recommended way to implement [queryable interfaces](/docs/reference/graphql-data-layer/schema-customization/#queryable-interfaces-with-the-nodeinterface-extension). +Now it is deprecated in favor of interface inheritance: + +```diff:title=gatsby-node.js +exports.createSchemaCustomization = function createSchemaCustomization({ actions }) { + const { createTypes } = actions + createTypes(` +- interface Foo @nodeInterface ++ interface Foo implements Node + { + id: ID! + } + `) +} +``` + +### JSON imports: follow the JSON modules web spec + +JSON modules are coming to the web. JSON modules only allow you to import the default export and no sub-properties. If you do import properties, you'll get a warning along these lines: + +``` +Should not import the named export 'myProp' from default-exporting module (only default export is available soon) +``` + +```diff:title=src/components/Navigation.js +import React from "react" +- import { items } from "../data/navigation.json" ++ import navigationData from "../data/navigation.json" + +const Navigation = () => ( + +) + +export default Navigation +``` + +### webpack deprecation messages + +When running community Gatsby plugins, you might see `[DEP_WEBPACK]` messages popup during the "Building JavaScript" or the "Building SSR bundle" phase. These often mean that the plugin is not compatible with webpack 5 yet. Contact the Gatsby plugin author or the webpack plugin author to flag this issue. Most of the time Gatsby will build fine, however there are cases that it won't and the reasons why could be cryptic. + +## Using `fs` in SSR + +Gatsby v3 introduces incremental builds for HTML generation. For this feature to work correctly, Gatsby needs to track all inputs used to generate HTML file. Arbitrary code execution in `gatsby-ssr.js` files allow usage of `fs` module, which is marked as unsafe and results in disabling of this feature. To migrate, you can use `import` instead of `fs`: + +```diff:title=gatsby-ssr.js +import * as React from "react" +-import * as fs from "fs" +-import * as path from "path" ++import stylesToInline from "!!raw-loader!/some-auto-generated.css" + +export function onRenderBody({ setHeadComponents }) { +- const stylesToInline = fs.readFileSync(path.join(process.cwd(), `some-auto-generated.css`)) + setHeadComponents( +