diff --git a/docs/contributing/blog-and-website-contributions.md b/docs/contributing/blog-contributions.md similarity index 85% rename from docs/contributing/blog-and-website-contributions.md rename to docs/contributing/blog-contributions.md index e42ea9ff7..bd0e82fee 100644 --- a/docs/contributing/blog-and-website-contributions.md +++ b/docs/contributing/blog-contributions.md @@ -1,21 +1,10 @@ --- -title: Blog & Website Contributions +title: Blog Contributions --- -We wholeheartedly welcome contributions to the Gatsby blog and website! +If you'd like to contribute a post to the Gatsby blog, please review the process and guidelines outlined below and submit your idea for the post to our [Gatsby blog proposal form](https://airtable.com/shr3449954866i3iF) -Here are some things to keep in mind when deciding where to contribute to Gatsby: - -- [Blog posts](#contributing-to-the-blog) work best for case studies and time-sensitive storytelling (see the [blog post format](#blog-post-format)). -- [Docs](/contributing/docs-contributions/) are continually relevant and discoverable learning materials that go beyond any one case study or situation. -- [Website changes](#making-changes-to-the-website) that improve either of these are always welcome! - -## Contributing to the blog - -If you'd like to contribute a post to the Gatsby blog, please review the process and guidelines outlined below and submit your -idea for the post to our [Gatsby blog proposal form](https://airtable.com/shr3449954866i3iF) - -### Blog proposal submission process +## Blog proposal submission process 1. Complete and submit the [Gatsby blog proposal form](https://airtable.com/shr3449954866i3iF). 2. A Gatsby team member will review your proposal and let you know if the proposal has been accepted within the next week or so. @@ -24,7 +13,7 @@ idea for the post to our [Gatsby blog proposal form](https://airtable.com/shr344 If you have any questions about the process or your submission, please email [marketing@gatsbyjs.com](mailto:marketing@gatsbyjs.com). -### Content guidelines for submitting a blog post proposal +## Content guidelines for submitting a blog post proposal As a Gatsby community member, you have unique insight into the ins and outs of learning Gatsby, building with Gatsby, and contributing to Gatsby’s open source community. Contributing to the Gatsby blog is a great way to share your experiences and insights. Here are some guidelines for what kind of content is and isn’t a good fit for the Gatsby blog. diff --git a/docs/contributing/code-contributions.md b/docs/contributing/code-contributions.md index 952cb2de2..be47d12a1 100644 --- a/docs/contributing/code-contributions.md +++ b/docs/contributing/code-contributions.md @@ -12,6 +12,7 @@ On this page: - [Contributing example sites](#contributing-example-sites) - [Using Docker to set up test environments](#using-docker-to-set-up-test-environments) - [Development tools](#development-tools) +- [Official theme development](#official-theme-development) ## Repo setup @@ -21,7 +22,7 @@ To start setting up the Gatsby repo on your machine using git, Yarn and Gatsby-C Alternatively, you can skip the local setup and [use an online dev environment](/contributing/using-an-online-dev-environment/). -To contribute to the blog or Gatsbyjs.org website, check out the setup steps on the [blog and website contributions](/contributing/blog-and-website-contributions/) page. For instructions on contributing to the docs, visit the [docs contributions page](/contributing/docs-contributions/). +To contribute to the blog, check out the setup steps on the [blog contributions](/contributing/blog-contributions/) page. For instructions on contributing to the docs, visit the [docs contributions page](/contributing/docs-contributions/). To contribute to the website, see the [website contributions](/contributing/website-contributions/) page. ## Creating your own plugins and loaders @@ -119,6 +120,22 @@ Using Docker Compose, you can start and stop a WordPress instance and integrate Check [Debugging the build process](/docs/debugging-the-build-process/) page to learn how to debug Gatsby. +## Official theme development + +This section is for official theme development in Gatsby's monorepo. If you are looking +to build your own theme, see [building themes](/docs/themes/building-themes/). + +Before getting started, make sure that you have +[set up your local dev environment](/contributing/setting-up-your-local-dev-environment/) +and that you're on the latest version of `gatsby-dev-cli`. + +- In the Gatsby monorepo find the starter in the `/starters` directory that uses the theme you want to work on +- Navigate to that directory, e.g. `cd starters/gatsby-starter-blog-theme` +- Install dependencies: `yarn` +- Run Gatsby Dev CLI to sync theme files, referencing the appropriate theme: `gatsby-dev --packages gatsby-theme-blog` +- In another tab run the starter: `yarn develop` +- Edit the theme files, you'll see changes automatically copied over and update in your starter. + ## Feedback At any point during the contributing process the Gatsby team would love to help! For help with a specific problem you can [open an issue on GitHub](/contributing/how-to-file-an-issue/). Or drop in to [our Discord server](https://gatsby.dev/discord) for general community discussion and support. diff --git a/docs/contributing/docs-and-website-components.md b/docs/contributing/docs-and-blog-components.md similarity index 83% rename from docs/contributing/docs-and-website-components.md rename to docs/contributing/docs-and-blog-components.md index 93c295345..39e4a501e 100644 --- a/docs/contributing/docs-and-website-components.md +++ b/docs/contributing/docs-and-blog-components.md @@ -1,13 +1,13 @@ --- -title: Docs and Website Components +title: Docs & Blog Components tableOfContentsDepth: 2 --- The Gatsbyjs.org site has a handful of components that have been developed to facilitate writing new content for the blog and the docs. There are also components that help organize and lay out content in various pages across the website. -This guide documents what components are available and explains how to use them. You can also refer to the [code for this page on GitHub](https://github.com/gatsbyjs/gatsby/blob/master/docs/contributing/docs-and-website-components.md) to see to how each component can be used, because they are all embedded here! +This guide documents what components are available and explains how to use them. You can also refer to the [code for this page on GitHub](https://github.com/gatsbyjs/gatsby/blob/master/docs/contributing/docs-and-blog-components.md) to see to how each component can be used, because they are all embedded here! -Information about authoring in Markdown and styling components on the site is also listed. +Information about authoring in Markdown on the site is also listed. ## Globally available components @@ -163,7 +163,7 @@ The Horizontal Nav List component takes two props: - `slug` - which is provided in the props of the page by default - `items` - an array of strings for items to render and wrap with a `` to subheadings -The docs on Gatsbyjs.org use the [gatsby-remark-autolink-headers](/packages/gatsby-remark-autolink-headers/) plugin to automatically apply hover links to heading tags across docs pages. Because it automatically creates links to subheadings on pages like the glossary, the Horizontal Nav List can supply matching links (like `"guide-list"` which would align with the automatically created link at `/docs/docs-and-website-components#guide-list`). +The docs on Gatsbyjs.org use the [gatsby-remark-autolink-headers](/packages/gatsby-remark-autolink-headers/) plugin to automatically apply hover links to heading tags across docs pages. Because it automatically creates links to subheadings on pages like the glossary, the Horizontal Nav List can supply matching links (like `"guide-list"` which would align with the automatically created link at `/docs/docs-and-blog-components#guide-list`). ```markdown @@ -188,14 +188,14 @@ The glossary defines key vocabulary... Rendered, it looks like this: --- @@ -271,19 +271,3 @@ plugins: [ ``` Line numbers and line highlighting can be added to code blocks as well, and is explained in detail in the [`gatsby-remark-prismjs` README](/packages/gatsby-remark-prismjs/?=remark#optional-add-line-highlighting-styles). - -## Styling components on Gatsbyjs.org with Theme-UI - -Styles on the site are applied using [Theme-UI](https://theme-ui.com/), which allows for theming across the site based on design tokens (also called variables). - -### Design tokens - -Design tokens are used to consolidate the number of colors and style attributes that are applied to components throughout the site. By limiting the styles that can be applied, the site stays consistent with the guidelines for color, typography, spacing, etc. - -Tables listing design tokens that are used on the site can be found in the [design guidelines](/guidelines/design-tokens/). - -### The `sx` prop - -The [`sx` prop](https://theme-ui.com/sx-prop) from Theme-UI allows you to access theme values to style elements and components, it should be used wherever possible. The prop is "enabled" by adding `theme-ui`'s [JSX pragma](https://theme-ui.com/jsx-pragma) at the top of a `js` file. - -It is still okay to directly import tokens, e.g. `mediaQueries` or `colors` directly from [`www/src/gatsby-plugin-theme-ui`](https://github.com/gatsbyjs/gatsby/blob/master/www/src/gatsby-plugin-theme-ui/index.js) if it helps your specific use case — for example when global CSS is required, when passing theme values to other libraries or plugins, when authoring complex responsive styles, etc. diff --git a/docs/contributing/docs-contributions.md b/docs/contributing/docs-contributions.md index 059dc284a..b9e587a0b 100644 --- a/docs/contributing/docs-contributions.md +++ b/docs/contributing/docs-contributions.md @@ -4,7 +4,7 @@ title: Docs Contributions Gatsby, unsurprisingly, uses Gatsby for its documentation website. Thank you in advance and cheers for contributing to Gatsby documentation! As of February 2019, over 800 people have contributed. It's people like you that make this community great! -> _When deciding where to contribute to Gatsby (docs or [blog](/contributing/blog-and-website-contributions/)?), check out the [docs templates](/contributing/docs-templates/) page._ +> _When deciding where to contribute to Gatsby (docs or [blog](/contributing/blog-contributions/)?), check out the [docs templates](/contributing/docs-templates/) page._ ## Top priorities @@ -190,7 +190,7 @@ Sometimes it makes sense to move or rename a file as part of docs restructuring ```yaml:title=www/redirects.yaml - fromPath: /docs/source-plugin-tutorial/ - toPath: /docs/pixabay-source-plugin-tutorial/ + toPath: /tutorial/pixabay-source-plugin-tutorial/ ``` ## Claim your swag diff --git a/docs/contributing/docs-writing-process.md b/docs/contributing/docs-writing-process.md new file mode 100644 index 000000000..6eccbe98a --- /dev/null +++ b/docs/contributing/docs-writing-process.md @@ -0,0 +1,96 @@ +--- +title: Docs Writing Process +--- + +When a new feature or integration is released that Gatsby developers can take advantage of, documentation should be added to improve the learning experience. Gatsby also needs docs for topic areas that exist in other technologies but are under-documented or under-tooled in the Gatsby ecosystem. + +The knowledge of how to work with a technique, source plugin, or varied use case may be known internally to Gatsby team members, but it also may only exist on the web at large. This contributing doc is intended to provide a written process for producing docs without prior information, a critical function of the Gatsby Learning team and open source community. + +## Identifying a topic + +When identifying a topic, start by: + +1. Looking at GitHub issues. Good labels to seek out are [`help wanted`](https://github.com/gatsbyjs/gatsby/issues?utf8=%E2%9C%93&q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22+) and [`good first issue`](https://github.com/gatsbyjs/gatsby/issues?q=is%3Aopen+is%3Aissue+label%3A%22good+first+issue%22). + + - This part may be covered if a docs issue is assigned to you, or if you’re signing up voluntarily to take on an issue. + +2. Look at the [stub list](/contributing/stub-list/) to find docs that need contributions. + +3. Look at the [learning workflow meta issue](https://github.com/gatsbyjs/gatsby/issues/13708) to find active areas looking for docs. + +4. Read through the existing Gatsby docs information and find gaps in topic coverage. Is there an area you feel is missing? [File an issue](/contributing/how-to-file-an-issue/) to discuss it. If the team determines it warrants documentation, implement in a PR. + +5. Observe common points of confusion or rough edges through user feedback and recommend solutions. + +> _Note: It’s required to open a GitHub issue before submitting a PR if one does not already exist._ + +## Selecting the correct format + +A GitHub issue for new learning material should indicate the format. Is it a Reference or Conceptual Guide? A Tutorial? A recipe? + +Does docs coverage exist anywhere on `gatsbyjs.org`? If so, would an alternative format help provide information for Gatsby learners of different skill and experience levels? For example, if a tutorial exists but there is no coverage in Reference Guides, adding more content in a different format would benefit users. + +### Tutorials vs. recipes vs. guides: + +- [**Tutorials**](/tutorial/) are step-by-step learning materials that show a user how to do something without skipping steps. Tutorials must consider a beginner experience, but can be useful for anyone. +- [**Recipes**](/docs/recipes/) are shorter, more concise tutorials that limit their scope to a single task or outcome by using prerequisites and limited steps. Additional resources at the end lead the user to a logical next step. Recipes are for developers of all skill levels. +- [**Guides**](/docs/guides/) are different than tutorials, and the two main sections are Reference Guides and Conceptual Guides. Instead of “steps 1-4”, guides use standalone headings and sections to explain how to accomplish the task. They are often aimed at a more advanced audience due to the subject matter but should be approachable to anyone. + +Given the difference in audiences of the three main learning material formats, increasing and overlapping coverage of topics can help support Gatsby learners of different skill and experience levels. + +Please follow the [Gatsby blog post guidelines](/contributing/blog-contributions/) and do not suggest blog posts when what is needed is user documentation. + +More on the format of documentation and learning materials can be found in the contributing docs: + +- [Docs Templates](/contributing/docs-templates/) +- [Gatsby Style Guide](/contributing/gatsby-style-guide/) + +## Gathering and validating supporting information + +Writing an effective doc that meets the needs of Gatsby users requires gathering information from various sources and applying those concepts to your original writing. You must digest and validate the details you uncover and understand them enough to describe them in a way that users of multiple skill levels can learn. + +Here are some tips for gathering information on a given topic within Gatsby: + +1. As you prepare a contribution that adds documentation information, carefully read the accompanying GitHub issue for tips and relevant materials, and ask questions there. + +2. Search the Gatsby GitHub repo for additional tips, examples, starters, plugins, READMEs, and other information that could help you provide a learning resource that guides users through a particular use case or concept. + +3. You can also search the web for additional examples outside of the Gatsby GitHub org or docs site. Be sure to check Gatsby versions and only reference the most current examples unless for a specific purpose. + +4. In the event there is no information available to write a greenfield doc after trying all the above steps, such as for a new integration, try interviewing Gatsby core team members to help to produce an outline and content tips. See [Pair Programming program](/contributing/pair-programming/). + +5. **For Gatsby inkteam members:** You can also search in the Gatsby Slack internally for related information. It’s possible other team members have discussed the issue, or even compiled trouble points into a doc. Look and ask around as part of your discovery work. + +After you’ve collected supporting information, you must produce original writing to be accepted in the Gatsby docs. Copying other blog posts, materials, or Gatsby team member interviews word-for-word without attribution is not acceptable or allowed. Furthermore, direct quotes from interviews are also _almost never_ effective for guides, recipes, or tutorials. + +Rather, the best way to write greenfield docs is with new text that explains the concepts and ideas you uncovered. With research and demos supporting your writing, you can speak more legitimately to use cases and common troubleshooting. Phrasing information in alternative ways for different skill levels is a bit like avoiding usage of the same word or phrase in its definition: if a reader didn’t understand it the first time, they may be more likely to understand it with an alternative explanation. + +## Producing learning materials + +Create demo sites and examples to provide more authoritative material that supports the developer experience. When relevant, **functioning source code is a requirement to writing docs** that truly educate users. Source code examples can also be linked from a doc as an additional resource. Include testing as part of your source code to ensure it is robust and stands the test of time. + +Follow the [docs templates](/contributing/docs-templates/) to ensure you’re producing content in the right format for its purpose. + +Use the [Markdown syntax doc](/docs/mdx/markdown-syntax/) to understand your options for formatting text with Markdown, and follow [accessibility recommendations](/docs/making-your-site-accessible/#how-to-improve-accessibility) for [heading levels](/contributing/docs-contributions/#headings) and image alt text. + +Run the docs site locally to check formatting and functionality. There are instructions in the [contributing docs](/contributing/docs-contributions/). + +Refer to the [Gatsby style guide](/contributing/gatsby-style-guide/) to ensure your PR will be accepted. + +## Submitting a pull request + +Submit a pull request that’s tied to a GitHub issue by following the [How to Open a Pull Request guide](/contributing/how-to-open-a-pull-request/). + +Apply feedback from pull request reviews in order for them to be accepted. Further instructions can be found in the How to Open a Pull Request guide. + +## Reference links + +- [Docs Contributions](/contributing/docs-contributions/) +- [Docs Templates](/contributing/docs-templates/) +- [How to File an Issue](/contributing/how-to-file-an-issue/) +- [Gatsby Style Guide](/contributing/gatsby-style-guide/) +- [Markdown Syntax Doc](/docs/mdx/markdown-syntax/) +- [Pair Programming](/contributing/pair-programming/) for interviewing the core team only +- [Blog Post Guidelines](/contributing/blog-contributions/) +- [Docs site setup instructions](/contributing/docs-contributions/#docs-site-setup-instructions) +- [How to Open a Pull Request](/contributing/how-to-open-a-pull-request/) diff --git a/docs/contributing/gatsby-style-guide.md b/docs/contributing/gatsby-style-guide.md index cbd7109c2..040c64652 100644 --- a/docs/contributing/gatsby-style-guide.md +++ b/docs/contributing/gatsby-style-guide.md @@ -126,19 +126,45 @@ Hyperlinks should contain the clearest words to indicate where the link will lea ```markdown -[Gatsby's docs](https://www.gatsbyjs.org/docs/) +[Gatsby Cloud](https://www.gatsbyjs.com/cloud/) -[here](https://www.gatsbyjs.org/docs/ "Gatsby's docs") +[here](https://www.gatsbyjs.com/cloud/ "Gatsby Cloud") ``` In tutorials that are meant for beginners, use as few hyperlinks as possible to minimize distractions. In docs, it's ok to include as many hyperlinks as necessary to provide relevant and interesting information and resources. +### Use relative hyperlinks for local links + +When referencing another page within [gatsbyjs.org](https://www.gatsbyjs.org/) hyperlinks should use relative paths (not include the full domain). This guarantees that all links function when running locally or in preview. + +```markdown + + +[Gatsby's glossary](/docs/glossary) + + + +[Gatsby's glossary](https://www.gatsbyjs.org/docs/glossary) +``` + +Note: Links to Gatsby Cloud/Gatsby Inc. are located at [gatsbyjs.com](https://www.gatsbyjs.com/) and should be referenced using an absolute path (domain included). See also [Referencing Gatsby Cloud](#referencing-gatsby-cloud) + ### Mark localhost URLs as code strings Unless you're running `gatsby develop` or `gatsby build` locally, localhost links will not work. Therefore it's recommended to list these URL references as code blocks so there aren't invalid links throughout the docs on Gatsbyjs.org. +```markdown + + +open your site with `http://localhost:8000/` + + + +open your site with [http://localhost:8000/](http://localhost:8000/) +``` + ### Indicate when something is optional When a paragraph or sentence offers an optional path, the beginning of the first sentence should indicate that it's optional. For example, "if you'd like to learn more about xyz, see our reference guide" is clearer than "Go to the reference guide if you'd like to learn more about xyz." @@ -282,10 +308,10 @@ You may also choose to include line highlighting in your code snippets, using th ````no-highlight ```javascript:title=gatsby-config.js module.exports = { - siteMetadata: { - title: `GatsbyJS`, // highlight-line - siteUrl: `https://www.gatsbyjs.org`, - }, + siteMetadata: { + title: `GatsbyJS`, // highlight-line + siteUrl: `https://www.gatsbyjs.org`, + }, } ``` ```` @@ -304,11 +330,11 @@ module.exports = { ````no-highlight ```javascript:title=gatsby-config.js module.exports = { - siteMetadata: { - title: `GatsbyJS`, - // highlight-next-line - siteUrl: `https://www.gatsbyjs.org`, - }, + siteMetadata: { + title: `GatsbyJS`, + // highlight-next-line + siteUrl: `https://www.gatsbyjs.org`, + }, } ``` ```` @@ -328,12 +354,12 @@ module.exports = { ````no-highlight ```javascript:title=gatsby-config.js module.exports = { - // highlight-start - siteMetadata: { - title: `GatsbyJS`, - siteUrl: `https://www.gatsbyjs.org`, - }, - // highlight-end + // highlight-start + siteMetadata: { + title: `GatsbyJS`, + siteUrl: `https://www.gatsbyjs.org`, + }, + // highlight-end } ``` ```` @@ -351,9 +377,12 @@ module.exports = { ### Capitalize proper nouns -Proper nouns should use correct capitalization when possible. Below is a list of words as they should appear in Guide articles. +Proper nouns should use correct capitalization when possible. Below is a list of words as they should appear in blog posts, docs, and other learning materials on this website. +- Gatsby +- GraphQL - JavaScript (capital letters in "J" and "S" and no abbreviations) +- Markdown - Node.js A full-stack developer (adjective form with a dash) works on the full stack diff --git a/docs/contributing/managing-pull-requests.md b/docs/contributing/managing-pull-requests.md index 3926efc93..c6f6b9299 100644 --- a/docs/contributing/managing-pull-requests.md +++ b/docs/contributing/managing-pull-requests.md @@ -65,7 +65,7 @@ For PRs that add a site or a starter to the showcase, we ought to check: For PRs that add a blog post, we ought to check: -- Approval – has the [blog post been approved](/contributing/blog-and-website-contributions/) by marketing or another Gatsby internal team? +- Approval – has the [blog post been approved](/contributing/blog-contributions/) by marketing or another Gatsby internal team? - Correctness — whether the added documentation is technically correct - Style — whether the written language follows our [style guide](/contributing/gatsby-style-guide/) - Subject matter — blog posts should not be purely promotional, spammy, or inappropriate. An author should check with a member of the Gatsby team that their post is appropriate for the blog before creating their PR. diff --git a/docs/contributing/pair-programming.md b/docs/contributing/pair-programming.md index 193e43726..d34a5eea9 100644 --- a/docs/contributing/pair-programming.md +++ b/docs/contributing/pair-programming.md @@ -30,8 +30,10 @@ We also expect the following from pair programming participants: ## How to sign up -We allow booking up to 30 days in advance, and spots tend to fill up fast. If we’re all booked up today, check back tomorrow for the next batch of spots. The core team is spread across North America, India, and Europe, so most time zones will have availability during working hours. +Fill in the [request a pairing session form][cal] to reserve your spot. The Gatsby team will be notified. You should get an email shortly with next steps. + +**Note:** Pairing sessions are currently paused as we establish a new process that will include recording so we can create lasting resources for the community from these sessions. We'll reach out to set up a time that works for you once we have the details ironed out. The core team is spread across North America, India, and Europe, so most time zones will have availability during working hours. [Reserve your spot today][cal] and let’s build something amazing together! -[cal]: https://calendly.com/gatsbyjs/pair-programming +[cal]: https://gatsby.dev/register-pair-programming diff --git a/docs/contributing/setting-up-your-local-dev-environment.md b/docs/contributing/setting-up-your-local-dev-environment.md index 9538fe499..6634e76f3 100644 --- a/docs/contributing/setting-up-your-local-dev-environment.md +++ b/docs/contributing/setting-up-your-local-dev-environment.md @@ -2,7 +2,7 @@ title: Setting Up Your Local Dev Environment --- -This page outlines how to get set up to contribute to Gatsby core and its ecosystem. For instructions on working with docs, visit the [docs contributions](/contributing/docs-contributions/) page. For blog and website setup instructions, visit the [blog and website contributions](/contributing/blog-and-website-contributions/) page. +This page outlines how to get set up to contribute to Gatsby core and its ecosystem. For instructions on working with docs, visit the [docs contributions](/contributing/docs-contributions/) page. For website setup instructions, visit the [website contributions](/contributing/website-contributions/) page. > Gatsby uses a "monorepo" pattern to manage its many dependencies and relies on > [Lerna](https://lerna.js.org/) and [Yarn](https://yarnpkg.com/en/) to configure the repository for both active development and documentation infrastructure changes. diff --git a/docs/contributing/site-showcase-submissions.md b/docs/contributing/site-showcase-submissions.md index f58a224bb..d514852de 100644 --- a/docs/contributing/site-showcase-submissions.md +++ b/docs/contributing/site-showcase-submissions.md @@ -71,7 +71,7 @@ Categories currently include both _type of site_ (structure) and the _content of - Blog - Directory - Documentation -- eCommerce +- E-commerce - Education - Portfolio - Gallery diff --git a/docs/contributing/submit-to-creator-showcase.md b/docs/contributing/submit-to-creator-showcase.md index b36b0fc06..58cc9b611 100644 --- a/docs/contributing/submit-to-creator-showcase.md +++ b/docs/contributing/submit-to-creator-showcase.md @@ -34,8 +34,8 @@ There are only two major steps :) development using Static Site Generators, Headless CMS, CI / CD and CDN setup. location: Poland - website: "https://yourname.io/" - github: "https://github.com/githubusername" + website: https://yourname.io/ + github: https://github.com/githubusername image: images/image.jpg # Right now, you can only answer true to either `for_hire` or for `hiring`, but not for both. diff --git a/docs/contributing/translation/maintainers.md b/docs/contributing/translation/maintainers.md index 9fa21b515..45487215b 100644 --- a/docs/contributing/translation/maintainers.md +++ b/docs/contributing/translation/maintainers.md @@ -14,7 +14,7 @@ As repo maintainers and members of the Gatsby community, your responsibilities a - Act as point of contact for your language and answer questions from both contributors to your language and the core Gatsby team. - Set up a process in order to get your translation published. (details to come) -As a maintainer, you are welcome to add a contributing doc written in your language to assist with the process. You can find an example in the [gatsby-es repo](https://github.com/gatsbyjs/gatsby-es/blob/master/CONTRIBUTING.MD). Translating [this page](https://github.com/gatsbyjs/gatsby/blob/master/docs/contributing/gatsby-docs-translation-guide.md) and copying it into a `contributing.md` file would be an option as well. +As a maintainer, you are welcome to add a contributing doc written in your language to assist with the process. You can find an example in the [gatsby-es repo](https://github.com/gatsbyjs/gatsby-es/blob/master/CONTRIBUTING.MD). Translating files from the folder [`docs/contributing/translation`](https://github.com/gatsbyjs/gatsby/tree/master/docs/contributing/translation) and copying it into a `contributing.md` file would be an option as well. ## Tips @@ -40,7 +40,7 @@ The Gatsby learning team is in charge of determining priorities for which docs s Don't be afraid to ask for help! If you're not sure about something, you can post in the `#localization` channel on the [Gatsby Discord](https://gatsby.dev/discord) or create an issue in the Gatsby repo. -If it feels like there is too much work and you need help, you have the ability to to add more codeowners by editing the `CODEOWNERS` file in the repo. Are there any contributors who are making exceptional contributions? If so, consider making them a codeowner. +If it feels like there is too much work and you need help, you have the ability to add more codeowners by editing the `CODEOWNERS` file in the repo. Are there any contributors who are making exceptional contributions? If so, consider making them a codeowner. We also understand that life sometimes gets in the way. If you find that you are no longer able to satisfy your codeowner duties, let the Gatsby team know so we can figure out the best path forward. diff --git a/docs/contributing/translation/new-translations.md b/docs/contributing/translation/new-translations.md index 5dc91e98b..543e57f25 100644 --- a/docs/contributing/translation/new-translations.md +++ b/docs/contributing/translation/new-translations.md @@ -2,7 +2,7 @@ title: Starting a New Translation --- -This page lists the steps to take to create a a new Gatsbyjs.org translation. +This page lists the steps to take to create a new Gatsbyjs.org translation. ## Creating a translation @@ -20,7 +20,7 @@ If you don't see the language among the issues listed, feel free to create a new ### Finding codeowners -For a new translation, open an issue with information about your intended language. If you already have co-contributors to act as fellow [code owners](https://help.github.com/en/articles/about-code-owners) and provide checks and balances for PR reviews and quality assurance, that would be very helpful! Otherwise, you can check out other [translation request issues](https://github.com/gatsbyjs/gatsby/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+%22New+Translation+Request%22) people have made and offer to join, or [get in touch with us](/contributing/how-to-contribute/#not-sure-how-to-start-contributing) at Gatsby for help in building your translation team. +For a new translation, open an issue with information about your intended language. If you already have co-contributors to act as fellow [code owners](https://help.github.com/en/github/creating-cloning-and-archiving-repositories/about-code-owners) and provide checks and balances for PR reviews and quality assurance, that would be very helpful! Otherwise, you can check out other [translation request issues](https://github.com/gatsbyjs/gatsby/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+%22New+Translation+Request%22) people have made and offer to join, or [get in touch with us](/contributing/how-to-contribute/#not-sure-how-to-start-contributing) at Gatsby for help in building your translation team. ## Criteria for translation approval diff --git a/docs/contributing/translation/sync-guide.md b/docs/contributing/translation/sync-guide.md index c2d87117d..4e652cc81 100644 --- a/docs/contributing/translation/sync-guide.md +++ b/docs/contributing/translation/sync-guide.md @@ -1,13 +1,42 @@ --- title: Keeping Translations Up-to-date -issue: https://github.com/gatsbyjs/gatsby/issues/21250 --- -Periodically, gatsbybot will create pull requests to keep translations repos up-to-date with the original English source. Make sure to review these PRs to ensure that your translation remains accurate. +Periodically, gatsbybot will update your translation repo to be up-to-date with the current English repo. If there is an update to a page that is already translated, gatsbybot will create a pull request listing the conflicts between translation and the new English content. Resolving these conflicts and merging these pull requests is essential to keeping your translation repo up-to-date. -> Note: the bot doesn't work yet but will come soon. Until then, see the next section to learn how to manually sync your repo. +## Resolving sync pull requests -### Manually syncing translation repos +When it runs the sync script, gatsbybot will create up to two pull requests. One is named: + +```text +(sync) Sync with gatsby-i18n-source @ {hash} +``` + +This pull request contains updates to all files that do not have conflicts. This includes files that have not been translated yet, and files that have been added to Gatsby. In general, these files can be merged in as-is, but it may be worth looking over them to see if there are any new files that were added to the repo that need to be translated. + +> 🚨NOTE: Make sure you do **NOT** choose the ["Squash and merge"](https://help.github.com/en/github/administering-a-repository/about-merge-methods-on-github#squashing-your-merge-commits) option when merging this pull request. Squashing will result in Git losing information about the sync, and will lead to extra conflicts on your next sync. Always make sure that you use the "Merge pull request" option. + +The second pull request will be named: + +```text +(sync) Resolve conflicts with gatsby-i18n-source @ {hash} +``` + +This pull request will list files that have conflicts between translated content and English content. These updates will appear as Git conflicts: + +```diff ++ <<<<<<< HEAD +Ahora, el componente `Box` estará al pendiente del estado de la transición de la página que es hijo, y aparecerá de entrada/salida en consecuencia. ++ ======= ++ Now, the `Box` component will be aware of whether the page it's a child of is mounting or unmounting, and it will fade in/out accordingly. ++ >>>>>>> 90932a06db2e297cf416552b84e48b4b82e56fbc +``` + +Here, the top block is the original translated line and the bottom block is the updated source content. You should resolve these conflicts by updating the top block to reflect the content of the bottom block. + +You may use whatever tools you like to resolve these conflicts: the GitHub UI, the command line, or a code editor like VS Code. See the [Common types of merge issues](#common-types-of-merge-issues) section for how to resolve various conflicts. + +## Manually syncing translation repos If for whatever reason you'd like to manually sync your translation repo, you can do so by running these commands: @@ -17,3 +46,126 @@ git pull source master ``` Fix all [merge conflicts](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/resolving-a-merge-conflict-using-the-command-line) and create a pull request to finish the merge. + +## Common types of merge issues + +### Frontmatter changes + +This type of conflict reflects a change to the [frontmatter](/docs/adding-markdown-pages/#frontmatter-for-metadata-in-markdown-files) of a document. + +Removing a field: + +```diff ++ <<<<<<< +title: my stub article +issue: #12345 ++ ======= ++ title: My Stub Article ++ >>>>>>> +``` + +Adding a field: + +```diff ++ <<<<<<< +title: Documentation ++ ======= ++ title: Docs ++ description: The one-stop shop for documentation in Gatsby! ++ >>>>>>> +``` + +Changing a field: + +```diff ++ <<<<<<< +title: My old title ++ ======= ++ title: My new title ++ >>>>>>> +``` + +### Typos fixes + +Sometimes there is a typo or grammatical error in the English source that gets fixed in an update. + +```diff +- Let's all use Gabsty! ++ Let's all use Gatsby! +``` + +```diff +- Gatsby is awesome framework! ++ Gatsby is an awesome framework! +``` + +Since these typos most likely don't exist in the translated version, you can most likely use the translated version as-is. + +### Formatting changes + +Sometimes the only difference is a change in formatting, such as adding back-ticks to annotate something as code, or changing the level of headings: + +```diff +- Sass files have the extension .scss. ++ Sass files have the extension `.scss`. +``` + +```diff +- #### Formatting changes ++ ### Formatting changes +``` + +The only necessary change is to ensure the translated content carries over these formatting updates. + +### Link updates + +These changes involve updating the URL of a link: + +```diff +- Please see our [plugins page](/packages). ++ Please see our [plugins page](/plugins). +``` + +```diff +- Check out our [GitHub](http://github.com/gatsbyjs/gatsby) ++ Check out our [GitHub](https://github.com/gatsbyjs/gatsby) +``` + +Resolve these changes by updating the link. + +### Content changes + +Sometimes, the content of the source page is actually updated and needs a translation. Make sure to read the change carefully and change the translation to match its meaning. + +### Conflicts in untranslated files + +Sometimes, you may find conflicts in files that haven't been translated yet: + +```diff ++ <<<<<<< +This is old English content. ++ ======= ++ This is new English content. ++ >>>>>>> +``` + +This is usually because of a previous improper merge (for example, using the "Squash and merge" option). In this case, it's usually alright to accept the new content. In VS Code, this is done using the "Accept Incoming Change" option: + +```diff +- This is old English content. ++ This is new English content. +``` + +## Creating a separate pull request + +If a page has significant changes, it may be worth splitting it into its own pull request: + +```shell +git checkout conflicts-9032a0 +git checkout -b sync-tutorial-0 +# Fix conflicts in /docs/tutorial/part-zero/index.md +git commit -am "Fix conflicts in tutorial part zero" +git push -u origin sync-tutorial-0 +``` + +Once the branch is pushed, create a pull request for branch `sync-tutorial-0` with `conflicts-9032a0` as the base branch. diff --git a/docs/contributing/translation/translators.md b/docs/contributing/translation/translators.md index f072f4ac3..e64725248 100644 --- a/docs/contributing/translation/translators.md +++ b/docs/contributing/translation/translators.md @@ -39,4 +39,4 @@ If you would like to be a maintainer of an existing translation repo, submit a P ## When a contributor will be removed -Consistent with the [Code of Conduct](/docs/code-of-conduct/) the Gatsby team reserves the right to remove a contributor (including translation maintainers) from the Gatsby organization if necessary. Some reasons for being removed include spammy comments, closing PRs or issues without action or productive dialogue, or generally harmful or abusive behavior inconsistent with Gatsby's policies. +Consistent with the [Code of Conduct](/contributing/code-of-conduct/) the Gatsby team reserves the right to remove a contributor (including translation maintainers) from the Gatsby organization if necessary. Some reasons for being removed include spammy comments, closing PRs or issues without action or productive dialogue, or generally harmful or abusive behavior inconsistent with Gatsby's policies. diff --git a/docs/contributing/translation/ui-messages.md b/docs/contributing/translation/ui-messages.md new file mode 100644 index 000000000..88b48c0c6 --- /dev/null +++ b/docs/contributing/translation/ui-messages.md @@ -0,0 +1,120 @@ +--- +title: Translating UI Messages +--- + +Most content that needs to be translated is in Markdown files in translation repos. However, Gatsbyjs.org also has several pieces of UI text that should be translated using a library called [Lingui](https://lingui.js.org/). + +## Message Translation Guide + +Unlike Markdown documents, UI messages are kept in the same monorepo as the gatsby source. + +1. Follow the instructions for [running the Gatsby website](/contributing/website-contributions/). +2. Go to `www/` and run `yarn lingui:add-locale [lang code]` to generate a file for your language at `src/data/locales/[lang-code]/messages.po`. +3. Translate all the strings in `[lang code]/messages.po` by editing the `msgstr` field of each message. + +```po +#: src/components/prev-and-next.js:51 +msgid: "Previous" +msgstr: "前" +``` + +## Translating rich content + +Some messages will have embedded numerical tags in them. These represent embedded components, formatting, or user-defined text and should be kept in the translated string. If you are unsure about the context of a tag, make sure to look at the source file of the message. + +The sections below list the different types of rich content you may encounter. + +### Self-closing tags + +This type of rich text consists of a single self-closing XML tag (e.g. `<0/>`): + +```po +#: src/components/markdown-page-footer.js:24 +msgid: "<0/> edit this page on GitHub" +msgstr: "" +``` + +These are usually icons embedded in the text: + +```jsx + + Edit this page on GitHub + +``` + +If you are translating a right-to-left language like Arabic, make sure the icons are in the proper position at the start or end of the text. + +### Opening and closing tags + +This type of rich text consists of matching XML tags (e.g. `<0>` and ``): + +```po +#: src/components/shared/egghead-embed.js:39 +msgid: "Video hosted on <0>egghead.io" +msgstr: "" +``` + +These can represent formatting, accessible text, or links: + +```jsx + + Video hosted on egghead.io + +``` + +Make sure that the tags are paired correctly and surround the corresponding text in the translation. + +### Interpolated text + +This rich text is represented by braces and a number (e.g. `{0}`): + +```po +#: src/components/sidebar/section-title.js:142 +msgid: "{0} collapse" +msgstr: "" +``` + +These represent text in interpolated strings: + +```javascript +t`${item.title} collapse` +``` + +## Plurals, formatting, and grammatical gender + +Right now, no text with complex formatting rules is available for translation. When it is, this guide will be updated. + +## Updating content + +Sometimes additional content is added to the UI, leading to untranslated text. When this occurs, please update your language's `messages.po` file with the new translations. + +### New messages + +New messages can be found by searching for `msgstr: ""`. These messages may be translated as usual. + +### Updated message text + +If a previously translated UI message has changed, Lingui will mark that message as outdated and create a new entry for the updated text: + +```po +#: src/components/prev-and-next.js:51 +#msgid: "Previous" +#msgstr: "前" + +#: src/components/prev-and-next.js:51 +msgid: "Previous Article" +msgstr: "" +``` + +Translate the updated entry and delete the old one: + +```diff +- #: src/components/prev-and-next.js:51 +- #msgid: "Previous" +- #msgstr: "前" + +#: src/components/prev-and-next.js:51 +msgid: "Previous Article" +- msgstr: "" ++ msgstr: "前の記事" +``` diff --git a/docs/contributing/website-contributions.md b/docs/contributing/website-contributions.md new file mode 100644 index 000000000..21786e1d3 --- /dev/null +++ b/docs/contributing/website-contributions.md @@ -0,0 +1,31 @@ +--- +title: Website Contributions +--- + +If you want to make changes, improvements, or add new functionality to the website, you don't have to set up the full Gatsby repo to contribute. You can spin up your own instance of the Gatsby website with these steps: + +- Clone [the Gatsby repo](https://github.com/gatsbyjs/gatsby/) and navigate to `/www` +- Run `yarn` to install all of the website's dependencies. +- Run `npm run develop` to preview the site at `http://localhost:8000/`. + +> Note: If you are experiencing issues on a Linux machine, run `sudo apt install libvips-dev`, to install a native dependency. You can also reference [Gatsby guide on Linux](/docs/gatsby-on-linux/) for other Linux-specific requirements. + +Now you can make and preview your changes before raising a pull request! + +For full repo setup instructions, visit the [code contributions](/contributing/code-contributions/) page. + +## Styling components on Gatsbyjs.org with Theme-UI + +Styles on the site are applied using [Theme-UI](https://theme-ui.com/), which allows for theming across the site based on design tokens (also called variables). + +### Design tokens + +Design tokens are used to consolidate the number of colors and style attributes that are applied to components throughout the site. By limiting the styles that can be applied, the site stays consistent with the guidelines for color, typography, spacing, etc. + +Tables listing design tokens that are used on the site can be found in the [design guidelines](/guidelines/design-tokens/). + +### The `sx` prop + +The [`sx` prop](https://theme-ui.com/sx-prop) from Theme-UI allows you to access theme values to style elements and components, it should be used wherever possible. The prop is "enabled" by adding `theme-ui`'s [JSX pragma](https://theme-ui.com/jsx-pragma) at the top of a `js` file. + +It is still okay to directly import tokens, e.g. `mediaQueries` or `colors` directly from [`www/src/gatsby-plugin-theme-ui`](https://github.com/gatsbyjs/gatsby/blob/master/www/src/gatsby-plugin-theme-ui/index.js) if it helps your specific use case — for example when global CSS is required, when passing theme values to other libraries or plugins, when authoring complex responsive styles, etc. diff --git a/docs/docs/adding-an-rss-feed.md b/docs/docs/adding-an-rss-feed.md index 2304a0620..05784edc4 100644 --- a/docs/docs/adding-an-rss-feed.md +++ b/docs/docs/adding-an-rss-feed.md @@ -159,7 +159,8 @@ module.exports = { } `, /* highlight-start */ - setup: () => ({ + setup: options => ({ + ...options, custom_namespaces: { itunes: 'http://www.itunes.com/dtds/podcast-1.0.dtd', }, diff --git a/docs/docs/adding-analytics.md b/docs/docs/adding-analytics.md index 1c66c8b27..b880027f2 100644 --- a/docs/docs/adding-analytics.md +++ b/docs/docs/adding-analytics.md @@ -69,3 +69,4 @@ Google Analytics アカウントと Gatsby のプラグインには、共に膨 - [Matomo (formerly Piwik)](/packages/gatsby-plugin-matomo/) - [Simple Analytics](/packages/gatsby-plugin-simple-analytics) - [Parse.ly Analytics](/packages/gatsby-plugin-parsely-analytics/) +- [GoatCounter](/packages/gatsby-plugin-goatcounter/) diff --git a/docs/docs/adding-redux-store.md b/docs/docs/adding-redux-store.md new file mode 100644 index 000000000..8c033b0bd --- /dev/null +++ b/docs/docs/adding-redux-store.md @@ -0,0 +1,12 @@ +--- +title: "Adding a Redux Store" +--- + +[Redux](https://redux.js.org/) helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test; that’s why Gatsby uses it as a core technology under the hood. On top of that, Redux provides a great developer experience, such as [live code editing combined with a time-traveling debugger](https://github.com/reduxjs/redux-devtools). + +In order to use Redux for **custom** state management in a Gatsby site, you'll need to hook into two of Gatsby's extension points: + +- Wrap the root element in your Gatsby markup once using `wrapRootElement`, an API supporting both Gatsby’s server rendering and browser JavaScript processes. +- Create a custom Redux store with reducers and initial state, providing your own state management functionality outside of Gatsby. + +Check out the Using Redux example with [./gatsby-ssr.js](https://github.com/gatsbyjs/gatsby/blob/master/examples/using-redux/gatsby-ssr.js) and [./gatsby-browser.js](https://github.com/gatsbyjs/gatsby/blob/master/examples/using-redux/gatsby-browser.js) files to see how this is implemented. You can also check out more information on the official [Redux](https://redux.js.org/introduction/getting-started) docs. diff --git a/docs/docs/api-proxy.md b/docs/docs/api-proxy.md index 3c9fcfeb7..51e7b9004 100644 --- a/docs/docs/api-proxy.md +++ b/docs/docs/api-proxy.md @@ -47,13 +47,16 @@ Keep in mind that `proxy` only has effect in development (with `gatsby develop`) Sometimes you need more granular/flexible access to the development server. Gatsby exposes the [Express.js](https://expressjs.com/) development server to your site's `gatsby-config.js` where you can add Express middleware as needed. ```javascript:title=gatsby-config.js -var proxy = require("http-proxy-middleware") +const { createProxyMiddleware } = require("http-proxy-middleware") //v1.x.x +// Use implicit require for v0.x.x of 'http-proxy-middleware' +// const proxy = require('http-proxy-middleware') +// be sure to replace 'createProxyMiddleware' with 'proxy' where applicable module.exports = { developMiddleware: app => { app.use( "/.netlify/functions/", - proxy({ + createProxyMiddleware({ target: "http://localhost:9000", pathRewrite: { "/.netlify/functions/": "", @@ -71,12 +74,16 @@ Keep in mind that middleware only has effect in development (with `gatsby develo If you proxy to local APIs with self-signed certificates, set the option `secure` to `false`. ```javascript:title=gatsby-config.js -var proxy = require("http-proxy-middleware") +const { createProxyMiddleware } = require("http-proxy-middleware") //v1.x.x +// Use implicit require for v0.x.x of 'http-proxy-middleware' +// const proxy = require('http-proxy-middleware') +// be sure to replace 'createProxyMiddleware' with 'proxy' where applicable + module.exports = { developMiddleware: app => { app.use( "/.netlify/functions/", - proxy({ + createProxyMiddleware({ target: "http://localhost:9000", secure: false, // Do not reject self-signed certificates. pathRewrite: { diff --git a/docs/docs/awesome-gatsby-resources.md b/docs/docs/awesome-gatsby-resources.md index 2f80fc87f..fee9be5c2 100644 --- a/docs/docs/awesome-gatsby-resources.md +++ b/docs/docs/awesome-gatsby-resources.md @@ -46,6 +46,7 @@ See the [unofficial list of themes](https://gatsbytemplates.io/) - [Jason Lengstorf's "Learn stuff with Jason" playlist](https://www.youtube.com/playlist?list=PLz8Iz-Fnk_eTpvd49Sa77NiF8Uqq5Iykx) - [Gatsby Days Bay Area December 2018 - Kyle Mathews & Guest Speakers](https://www.youtube.com/playlist?list=PLCU2qJekvcN1wzgVKymbjbGtZ3VgAWOdj) - [Static Site Generation with Gatsby.js v0 — Scott Nonnenberg](https://blog.scottnonnenberg.com/static-site-generation-with-gatsby-js/) +- [Build a JAMstack Saas App with Gatsby playlist](https://www.youtube.com/playlist?list=PL8KiuH6vpACWZ7989jU1Puil5P2_m2O8e) - [React.js Conf 2016 - Lightning Talks - Kyle Mathews](https://www.youtube.com/watch?v=RFkNRKL6ZoE) - [Developing with React and Gatsby.js — Kyle Mathews](https://www.youtube.com/watch?v=G4LVKJOOj7o) - [GraphQL Summit Open Source Lightning Talk on Gatsby — Kyle Mathews](https://youtu.be/y588qNiCZZo) @@ -54,6 +55,7 @@ See the [unofficial list of themes](https://gatsbytemplates.io/) ## Livestreams - [Learn with Jason](https://www.youtube.com/playlist?list=PLCU2qJekvcN0RuMHCnjMYAKlpSKQ_e1hO) +- [Build a Saas app with Gatsby and the JAMstack](https://www.youtube.com/playlist?list=PL8KiuH6vpACWZ7989jU1Puil5P2_m2O8e) ## Gatsby tutorials @@ -91,6 +93,7 @@ See the [unofficial list of themes](https://gatsbytemplates.io/) - [Deploying Your First Gatsby Site to Netlify](https://scotch.io/tutorials/deploying-your-first-gatsby-site-to-netlify) - [Add a chat widget to your Gatsby blog](https://pusher.com/tutorials/chat-gatsby/) - [Headless WordPress: Why Gatsby Should Be Next on Your List of Things to Learn](https://deliciousbrains.com/gatsby-headless-wordpress/) +- [Gatsby Tutorials \[video series\] — Michael Uloth](https://www.youtube.com/watch?v=jAa1wh5ATm0&list=PLHBEcHVSROXQQhXpNhmiVKKcw72Cc0V-U) ### German diff --git a/docs/docs/browser-support.md b/docs/docs/browser-support.md index eebaad9df..9b12f50bb 100644 --- a/docs/docs/browser-support.md +++ b/docs/docs/browser-support.md @@ -2,7 +2,7 @@ title: Browser Support --- -Gatsby supports [the same browsers as the current stable version of React.js](https://facebook.github.io/react/docs/react-dom.html#browser-support) which is currently IE9+ as well as the most recent versions of other popular browsers. +Gatsby supports [the same browsers as the current stable version of React.js](https://reactjs.org/docs/react-dom.html#browser-support) which is currently IE9+ as well as the most recent versions of other popular browsers. ## Polyfills diff --git a/docs/docs/building-an-e-commerce-site.md b/docs/docs/building-an-e-commerce-site.md index 6e48ffcc1..5eeecc638 100644 --- a/docs/docs/building-an-e-commerce-site.md +++ b/docs/docs/building-an-e-commerce-site.md @@ -1,5 +1,5 @@ --- -title: Building an e-commerce Site +title: Building an E-commerce Site --- The speed and performance of sites built with Gatsby make it a great tool for building e-commerce sites. There are existing plugins for connecting services like [Shopify](/packages/gatsby-source-shopify/) and [Snipcart](/packages/gatsby-plugin-snipcart/) to Gatsby, and this section contains reference guides to help get things setup. @@ -8,4 +8,4 @@ To see examples of e-commerce sites built with Gatsby, check out the [showcase]( -_You can also check out the ["Making an e-commerce Site with Stripe" tutorial](/tutorial/ecommerce-tutorial/) for more information._ +_You can also check out the ["Making an E-commerce Site with Stripe" tutorial](/tutorial/ecommerce-tutorial/) for more information._ diff --git a/docs/docs/building-an-ecommerce-site-with-shopify.md b/docs/docs/building-an-ecommerce-site-with-shopify.md index 2611b6c5a..28ae91030 100644 --- a/docs/docs/building-an-ecommerce-site-with-shopify.md +++ b/docs/docs/building-an-ecommerce-site-with-shopify.md @@ -1,5 +1,5 @@ --- -title: Building an e-commerce site with Shopify +title: Building an E-commerce site with Shopify --- In this tutorial, you will setup a new Gatsby website that fetches product data from [Shopify](https://www.shopify.com). The site displays a list of all products on a product listing page, and a page for every product in the store. diff --git a/docs/docs/building-with-components.md b/docs/docs/building-with-components.md index d72ce3144..e72dfa1a1 100644 --- a/docs/docs/building-with-components.md +++ b/docs/docs/building-with-components.md @@ -19,7 +19,7 @@ The following model shows how data from a source can be queried by GraphQL for u -[Thinking in React](https://facebook.github.io/react/docs/thinking-in-react.html) +[Thinking in React](https://reactjs.org/docs/thinking-in-react.html) is a good resource for learning how to structure applications with React. ## How does Gatsby use React Components? diff --git a/docs/docs/caching.md b/docs/docs/caching.md index 6e49e14b3..7f2d7b4cb 100644 --- a/docs/docs/caching.md +++ b/docs/docs/caching.md @@ -51,7 +51,12 @@ When deploying with Now, follow the instructions in the [Now documentation](http --- -1 You can use 'no-cache' instead of 'max-age=0, must-revalidate'. Despite what the name might imply, 'no-cache' permits a cache to serve cached content as long as it validates the cache freshness first. [2][3] In either case, clients have to make a round trip to the origin server on each request. However, if you are correctly utilizing ETags or Last-Modified validation you will avoid downloading assets when the cached copy is still valid (e.g. the file hasn't changed on the origin server since it was cached). + + 1 + You can use 'no-cache' instead of 'max-age=0, must-revalidate'. Despite what the name might imply, 'no-cache' permits a cache to serve cached content as long as it validates the cache freshness first. + + [2][3]{" "} + In either case, clients have to make a round trip to the origin server on each request. However, if you are correctly utilizing ETags or Last-Modified validation you will avoid downloading assets when the cached copy is still valid (e.g. the file hasn't changed on the origin server since it was cached). [2]: https://tools.ietf.org/html/rfc7234#section-5.2.2.1 [3]: https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching#no-cache_and_no-store diff --git a/docs/docs/cheat-sheet.md b/docs/docs/cheat-sheet.md index 91dad8bd9..edf2c654a 100644 --- a/docs/docs/cheat-sheet.md +++ b/docs/docs/cheat-sheet.md @@ -7,277 +7,457 @@ The Gatsby team has created a resource that you might find useful when building Get the PDF: gatsby-cheat-sheet.pdf
-

Page 1

- - Cheat Sheet - page 1 +

Page 1

+
+ Cheat Sheet - page 1 + +

Page 2

+ + Cheat Sheet - page 2 + +
+
+

Gatsby Cheat Sheet contents

+

+ v1.0 for Gatsby 2.x + + Latest version -

Page 2

- - Cheat Sheet - page 2 +

+

Top Docs

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+

Gatsby Docs

+
+

+ gatsby.dev/docs +

+
+

Gatsby on GitHub

+
+

+ + github.com/gatsbyjs/gatsby + +

+
+

Gatsby Tutorial

+
+

+ gatsby.dev/tutorial +

+
+

+ Quick Start +
+ (for intermediate and advanced developers) +

+
+

+ gatsby.dev/quick-start +

+
+

Gatsby Starters

+
+

+ gatsby.dev/starters +

+
+

Quick Reference Guide

+
+

+ gatsby.dev/recipes +

+
+

Adding Images

+
+

+ gatsby.dev/image +

+
+

Gatsby Node APIs

+
+

+ gatsby.dev/api +

+
+

Querying with GraphQL

+
+

+ gatsby.dev/graphql +

+
+

Deploying and Hosting

+
+

+ gatsby.dev/deploy +

+
+

Using Gatsby Link

+
+

+ gatsby.dev/link +

+
+

Static Query

+
+

+ + gatsby.dev/static-query + +

+
+

How to Contribute

+
+

+ gatsby.dev/contribute +

+
+

+ gatsbyjs.org +

+

+ twitter.com/gatsbyjs +

+

Gatsby CLI Commands

+

+ First, install the global executable: +
+ npm install -g gatsby-cli +

+

+ Run gatsby --help for a list of commands and options. +

+

+ + gatsby new my-site-name + +

+

+ Create a new local Gatsby site using the default starter (see “Quick Start + Commands” in this cheat sheet on how to use other starters). +

+

+ gatsby develop +

+

Start the Gatsby development server.

+ + + + + + + + + + + + + + + + + + + +
+

+ -H, --host +

+
+

+ Set host. Defaults to localhost +

+
+

+ -p, --port +

+
+

+ Set port. Defaults to env.PORT or 8000 +

+
+

+ -o, --open +

+
+

Open the site in your (default) browser for you

+
+

+ -S, --https +

+
+

Use HTTPS

+
+

+ gatsby build +

+

+ Compile your application and make it ready for deployment. +
+

+ + + + + + + + + + + + + + + +
+

+ --prefix-paths +

+
+

+ Build site with link paths prefixed +
+ (set pathPrefix in your config) +

+
+

+ --no-uglify +

+
+

+ Build site without uglifying JS bundles +
+ (for debugging) +

+
+

+ --open-tracing-config-file +

+
+

+ Tracer configuration file (OpenTracing compatible). See{" "} + gatsby.dev/tracing +

+
+

+ gatsby serve +

+

Serve the production build for testing.

+ + + + + + + + + + + + + + + + + + + +
+

+ -H, --host +

+
+

+ Set host. Defaults to localhost +

+
+

+ -p, --port +

+
+

+ Set port. Defaults to 9000 +

+
+

+ -o, --open +

+
+

Open the site in your (default) browser for you

+
+

+ --prefix-paths +

+
+

+ Serve site with link paths prefixed (if built with{" "} + pathPrefix in your gatsby-config.js) +

+
+

+ gatsby info +

+

+ Get helpful environment information which will be required when reporting a + bug at{" "} + + github.com/gatsbyjs/gatsby/issues - - -

-

Gatsby Cheat Sheet contents

-

v1.0 for Gatsby 2.x - Latest version -

-

Top Docs

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
-

Gatsby Docs

-
-

gatsby.dev/docs

-
-

Gatsby on GitHub

-
-

github.com/gatsbyjs/gatsby

-
-

Gatsby Tutorial

-
-

gatsby.dev/tutorial

-
-

Quick Start
(for intermediate and advanced developers)

-
-

gatsby.dev/quick-start

-
-

Gatsby Starters

-
-

gatsby.dev/starters

-
-

Quick Reference Guide

-
-

gatsby.dev/recipes

-
-

Adding Images

-
-

gatsby.dev/image

-
-

Gatsby Node APIs

-
-

gatsby.dev/api

-
-

Querying with GraphQL

-
-

gatsby.dev/graphql

-
-

Deploying and Hosting

-
-

gatsby.dev/deploy

-
-

Using Gatsby Link

-
-

gatsby.dev/link

-
-

Static Query

-
-

gatsby.dev/static-query

-
-

How to Contribute

-
-

gatsby.dev/contribute

-
-

gatsbyjs.org

-

twitter.com/gatsbyjs

-

Gatsby CLI Commands

-

First, install the global executable: -
- npm install -g gatsby-cli

-

Run gatsby --help for a list of commands and options.

-

gatsby new my-site-name

-

Create a new local Gatsby site using the default starter (see “Quick Start Commands” in this cheat sheet on how to use other starters).

-

gatsby develop

-

Start the Gatsby development server.

- - - - - - - - - - - - - - - - - - - -
-

-H, --host

-
-

Set host. Defaults to localhost

-
-

-p, --port

-
-

Set port. Defaults to env.PORT or 8000

-
-

-o, --open

-
-

Open the site in your (default) browser for you

-
-

-S, --https

-
-

Use HTTPS

-
-

gatsby build

-

Compile your application and make it ready for deployment.

- - - - - - - - - - - - - - - -
-

--prefix-paths

-
-

Build site with link paths prefixed
(set pathPrefix in your config)

-
-

--no-uglify

-
-

Build site without uglifying JS bundles
(for debugging)

-
-

--open-tracing-config-file

-
-

Tracer configuration file (OpenTracing compatible). See gatsby.dev/tracing

-
-

gatsby serve

-

Serve the production build for testing.

- - - - - - - - - - - - - - - - - - - -
-

-H, --host

-
-

Set host. Defaults to localhost

-
-

-p, --port

-
-

Set port. Defaults to 9000

-
-

-o, --open

-
-

Open the site in your (default) browser for you

-
-

--prefix-paths

-
-

Serve site with link paths prefixed (if built with pathPrefix in your gatsby-config.js)

-
-

gatsby info

-

Get helpful environment information which will be required when reporting a bug at github.com/gatsbyjs/gatsby/issues.

- - - - - - - -
-

-C, --clipboard

-
-

Automagically copy environment information to clipboard

-
-

gatsby clean

-

Wipe out Gatsby’s .cache and public directories.

-

T-Shirts, Hats, Hoodies, and more!

-

Sign up for the Gatsby Newsletter and get 30% off your Gatsby Store purchase! (gatsby.dev/store)

-

Sign up at gatsby.dev/discount

-

Quick Start Commands

-

Create a new Gatsby site using the “Blog” starter:
- gatsby new my-blog-starter https://github.com/gatsbyjs/gatsby-starter-blog

-

Navigate into your new site’s directory and start it up:
- cd my-blog-starter/
- gatsby develop

-

Your site is now running at http://localhost:8000!

-

You’ll also see a second link: http://localhost:8000/___graphql. This is a tool you can use to experiment with querying your data. Learn more about it at gatsby.dev/tutorial

-

For more Gatsby starters, visit gatsby.dev/starters.

-

Helpful File Definitions

-

Each of these files should live at the root of your Gatsby project folder. See gatsby.dev/projects

-

gatsby-config.js — configure options for a Gatsby site, with metadata for project title, description, plugins, etc.

-

gatsby-node.js — implement Gatsby’s Node.js APIs to customize and extend default settings affecting the build process

-

gatsby-browser.js — customize and extend default settings affecting the browser, using Gatsby’s browser APIs

-

gatsby-ssr.js — use Gatsby’s server-side rendering APIs to customize default settings affecting server-side rendering

+ . +

+ + + + + + + +
+

+ -C, --clipboard +

+
+

Automagically copy environment information to clipboard

+
+

gatsby clean

+

+ Wipe out Gatsby’s .cache and public directories. +

+

T-Shirts, Hats, Hoodies, and more!

+

+ Sign up for the Gatsby Newsletter and get 30% off your + Gatsby Store purchase! ( + gatsby.dev/store) +

+

+ Sign up at gatsby.dev/discount +

+

Quick Start Commands

+

+ Create a new Gatsby site using the “Blog” starter: +
+ + gatsby new my-blog-starter https://github.com/gatsbyjs/gatsby-starter-blog + +

+

+ Navigate into your new site’s directory and start it up: +
+ + cd my-blog-starter/ +
+ gatsby develop +
+

+

+ Your site is now running at http://localhost:8000! +

+

+ {/* prettier-ignore */} + You’ll also see a second link: http://localhost:8000/___graphql. + This is a tool you can use to experiment with querying your data. Learn more + about it at gatsby.dev/tutorial +

+

+ For more Gatsby starters, visit{" "} + gatsby.dev/starters. +

+

Helpful File Definitions

+

+ Each of these files should live at the root of your Gatsby project folder. + See gatsby.dev/projects +

+

+ gatsby-config.js — configure options for a Gatsby site, with + metadata for project title, description, plugins, etc. +

+

+ gatsby-node.js — implement Gatsby’s Node.js APIs to customize + and extend default settings affecting the build process +

+

+ gatsby-browser.js — customize and extend default settings + affecting the browser, using Gatsby’s browser APIs +

+

+ gatsby-ssr.js — use Gatsby’s server-side rendering APIs to + customize default settings affecting server-side rendering +

diff --git a/docs/docs/cli-feedback.md b/docs/docs/cli-feedback.md new file mode 100644 index 000000000..7a142a463 --- /dev/null +++ b/docs/docs/cli-feedback.md @@ -0,0 +1,9 @@ +--- +title: Gatsby CLI Feedback +--- + +Gatsby users will be prompted every 3 months (at the most) to give feedback on Gatsby's products and services. This feedback is incredibly valuable and will help the team shape Gatsby. + +## How to opt-out + +Users may always opt-out from the feedback prompts with `gatsby feedback --disable` or by setting the [environment variable](/docs/environment-variables/) `GATSBY_TELEMETRY_DISABLED` to `1`. diff --git a/docs/docs/configuring-usage-with-plugin-options.md b/docs/docs/configuring-usage-with-plugin-options.md new file mode 100644 index 000000000..e71909825 --- /dev/null +++ b/docs/docs/configuring-usage-with-plugin-options.md @@ -0,0 +1,59 @@ +--- +title: Configuring Plugin Usage with Plugin Options +--- + +Plugins loaded into a Gatsby site can have options passed in to customize how a plugin operates. + +_This guide refers to creating plugins, if you are looking for general information on using options with plugins refer to ["Using a Plugin in Your Site"](/docs/using-a-plugin-in-your-site/). If you are looking for options of a specific plugin, refer to its README._ + +## Where to access plugin options + +A Gatsby plugin with options included makes those options available in the second argument of Gatsby [Node](/docs/node-apis/), [Browser](/docs/browser-apis/), and [SSR APIs](/docs/ssr-apis/). Consider the following `gatsby-config` with a plugin called `gatsby-plugin-console-log`: + +```javascript:title=gatsby-config.js +module.exports = { + plugins: [ + { + resolve: `gatsby-plugin-console-log`, + options: { optionA: true, optionB: false, message: "Hello world" }, + }, + ], +} +``` + +With the `optionA`, `optionB`, and `message` options passed into the plugin, the code for `gatsby-plugin-console-log` is able to access the values `true`, `false`, and `Hello world` by their keys. + +For example, `gatsby-plugin-console-log` can access the `message` in order to log its value to the console inside of the `onPreInit` API: + +```javascript:title=plugins/gatsby-plugin-console-log/gatsby-node.js +exports.onPreInit = (_, pluginOptions) => { + console.log( + `logging: "${pluginOptions.message || `default message`}" to the console` // highlight-line + ) +} +``` + +The code above is called when `gatsby develop` or `gatsby build` is run. It takes the `message` from the `options` object in the config and logs it from `pluginOptions.message` when the `onPreInit` method is called. + +The second argument passed into the function is where the options are held. + +_Like arguments in any JavaScript function, you can use a different (more specific) name like `themeOptions` if you are building a plugin that will be used as a theme._ + +## What can be passed in as options + +Any JavaScript data type can be passed in as an option. + +The following table lists possible options values and an example plugin that makes use of them. + +| Data Type | Sample Value | Example Plugin | +| --------- | -------------------------------- | ----------------------------------------------------------------- | +| Boolean | `true` | [`gatsby-plugin-sharp`](/packages/gatsby-plugin-sharp/) | +| String | `/src/data/` | [`gatsby-source-filesystem`](/packages/gatsby-source-filesystem/) | +| Array | `["/about-us/", "/projects/*"]` | [`gatsby-plugin-offline`](/packages/gatsby-plugin-offline/) | +| Object | `{ default: "./src/layout.js" }` | [`gatsby-plugin-mdx`](/packages/gatsby-plugin-mdx/) | + +**Note**: Themes (which are a type of plugin) are able to receive options from a site's `gatsby-config` to be used in its `gatsby-config` in order to allow themes to be composed together. This is done by exporting the `gatsby-config` as a function instead of an object. You can see an example of this in the [`gatsby-theme-blog`](https://github.com/gatsbyjs/gatsby/tree/master/packages/gatsby-theme-blog) and [`gatsby-theme-blog-core`](https://github.com/gatsbyjs/gatsby/tree/master/packages/gatsby-theme-blog-core) repositories. Plugins are not capable of this functionality. + +## Additional resources + +- [Example Gatsby site using plugin options with a local plugin](https://github.com/gatsbyjs/gatsby/tree/master/examples/using-plugin-options) diff --git a/docs/docs/creating-a-generic-plugin.md b/docs/docs/creating-a-generic-plugin.md new file mode 100644 index 000000000..ea1d4091d --- /dev/null +++ b/docs/docs/creating-a-generic-plugin.md @@ -0,0 +1,60 @@ +--- +title: Creating a Generic Plugin +--- + +This section aims to explain the structure of a Gatsby plugin and the files you need to create one. + +The idea of a generic plugin is to lay more emphasis on the makeup of a plugin rather than the specific labels ([source](/docs/creating-a-source-plugin/), [transformer](/docs/creating-a-transformer-plugin/), [local](https://www.gatsbyjs.org/docs/creating-a-local-plugin/)) that are [selected based on functionality](/docs/naming-a-plugin/). As seen in the [what is a plugin doc](/docs/what-is-a-plugin/), a plugin is a piece of software that acts as an add-on and gives a Gatsby site additional functionality. + +Plugins contain a file, usually in the project root, called `package.json` - this file holds various metadata relevant to the project. The `package.json` file is also used to provide information to npm that identifies the project and allows npm to handle the project's dependencies. + +## Initializing your plugin project + +To initialize a `package.json` for your project, run the following command: + +```shell + npm init +``` + +Once you've run the command you'll see a series of options listed in the command-line interface (CLI). Those you select are stored in your `package.json` which contains some of the [files Gatsby looks for in a Plugin](/docs/files-gatsby-looks-for-in-a-plugin) + +## What happens in a generic plugin? + +In a generic plugin the `gatsby-node.js` file enables the use of [gatsby node APIs](/docs/node-apis/). These APIs, such as `createPage`, `createResolvers`, and `sourceNodes`, manipulate the Node(s) in a Gatsby site. A [Node](/docs/node-creation/) is the smallest unit of data in Gatsby. You can create a Node using the [createNode](/docs/actions/#createNode) action. + +In `gatsby-node.js` you can carry out functions with these APIs, such as: + +- Loading API keys +- Sending calls to APIs +- Creating Gatsby-nodes using the API response +- Creating Individual pages from nodes + +> A good use case of the above would be a plugin that gets data from an API. + +### An example of a generic plugin + +[sourceNodes](/docs/node-apis/#sourceNodes) is a life-cycle API that a plugin can use to create Nodes. An example of how to implement a function using `sourceNodes` is shown below: + +```javascript:title=gatsby-node.js +export.sourceNodes = ({ actions,createNodeID,createContentDigest})=>{ + const nodeData = { + title : "Test Node", + description:"Testing the node " + } + const newNode = { + ...nodeData, + id: createNodeId("TestNode-testid") + internal :{ + type: "TestNode" + contentDigest: createContentDigest(nodeData), + }, + } + actions.creatNode(newNode) +} +``` + +The above code block creates a node called `"Test Node"` as seen from the `title` parameter. If this process is successful restarting the server will make the `allTestNode` query available at `localhost:8000/___graphql`. + +> Libraries like [Axios](https://www.npmjs.com/package/axios) can be used to handle calls in the `gatsby-node.js` file + +Though all plugins have the same structure, their name signals what functionality they provide. See the [naming a plugin](/docs/naming-a-plugin) section for more information. diff --git a/docs/docs/creating-a-local-plugin.md b/docs/docs/creating-a-local-plugin.md index 1b2adffcf..f603ccc2c 100644 --- a/docs/docs/creating-a-local-plugin.md +++ b/docs/docs/creating-a-local-plugin.md @@ -8,7 +8,7 @@ If a plugin is only relevant to your specific use-case, or if you’re developin Place the code in the `plugins` folder in the root of your project like this: -``` +```text /my-gatsby-site └── gatsby-config.js └── /src @@ -36,6 +36,12 @@ Then the plugin can begin to hook into Gatsby through [Node](/docs/node-apis/) a Your plugin doesn't have to be in your project in order to be tested or worked on. If you'd like to [decouple](/docs/glossary#decoupled) your plugin from your site you can follow one of the methods described below. This is a useful thing to do if you want to publish the plugin as its own package, or test/develop a forked version of a community authored plugin. +To get started developing a plugin outside of your site's root folder, you can quickly generate one using `gatsby new` with the [starter for plugins](https://github.com/gatsbyjs/gatsby/tree/master/starters/gatsby-starter-plugin): + +```shell +gatsby new gatsby-plugin-foo https://github.com/gatsbyjs/gatsby-starter-plugin +``` + ### Using `require.resolve` and a filepath Including a `plugins` folder is not the only way to reference a local plugin. Alternatively, you can include a plugin in your `gatsby-config.js` file by directly referencing its path (relative to the `gatsby-config.js` file) with `require`. diff --git a/docs/docs/creating-a-source-plugin.md b/docs/docs/creating-a-source-plugin.md index 4572c90eb..0af8ac02d 100644 --- a/docs/docs/creating-a-source-plugin.md +++ b/docs/docs/creating-a-source-plugin.md @@ -6,7 +6,7 @@ Source plugins are essentially out of the box integrations between Gatsby and va These systems can be CMSs like Contentful or WordPress, other cloud services like Lever and Strava, or your local filesystem -- literally anything that has an API. Currently, Gatsby has [over 300 source plugins](/plugins/?=gatsby-source). -Once a source plugin brings data into Gatsby's system, it can be transformed further with **transformer plugins**. +Once a source plugin brings data into Gatsby's system, it can be transformed further with **transformer plugins**. For step-by-step examples of how to create source and transformer plugins, check out the Gatsby [tutorials section](/tutorial/plugin-and-theme-tutorials/). ## What do source plugins do? @@ -40,7 +40,7 @@ exports.sourceNodes = async ({ actions }) => { // Process data into nodes. data.forEach(datum => createNode(processDatum(datum))) - // We're done, return. + // You're done, return. return } ``` @@ -157,4 +157,8 @@ One tip to improve the development experience of using a plugin is to reduce the - **Add event-based sync**. Some data sources keep event logs and are able to return a list of objects modified since a given time. If you're building a source plugin, you can store the last time you fetched data using [`setPluginStatus`](/docs/actions/#setPluginStatus) and then only sync down nodes that have been modified since that time. [gatsby-source-contentful](https://github.com/gatsbyjs/gatsby/tree/master/packages/gatsby-source-contentful) is an example of a source plugin that does this. -- **Proactively fetch updates**. One challenge when developing locally is that a developer might make modifications in a remote data source, like a CMS, and then want to see how it looks in the local environment. Typically they will have to restart the `gatsby develop` server to see changes. This can be avoided if your source plugin knows to proactively fetch updates from the remote server. For example,[gatsby-source-sanity](https://github.com/sanity-io/gatsby-source-sanity), listens to changes to Sanity content when `watchMode` is enabled and pulls them into the Gatsby develop server. +- **Proactively fetch updates**. One challenge when developing locally is that a developer might make modifications in a remote data source, like a CMS, and then want to see how it looks in the local environment. Typically they will have to restart the `gatsby develop` server to see changes. This can be avoided if your source plugin knows to proactively fetch updates from the remote server. For example, [gatsby-source-sanity](https://github.com/sanity-io/gatsby-source-sanity), listens to changes to Sanity content when `watchMode` is enabled and pulls them into the Gatsby develop server. + +## Additional resources + +- Tutorial: [Creating a Pixabay Image Source Plugin](/tutorial/pixabay-source-plugin-tutorial/) diff --git a/docs/docs/creating-a-transformer-plugin.md b/docs/docs/creating-a-transformer-plugin.md index f0d0206bd..5ec01d2a7 100644 --- a/docs/docs/creating-a-transformer-plugin.md +++ b/docs/docs/creating-a-transformer-plugin.md @@ -15,6 +15,8 @@ The purpose of this doc is to: 1. Define what a Gatsby transformer plugin is, and 2. Walk through a simplified reimplementation of an existing plugin, to demonstrate how to create a transformer plugin. +For a step-by-step process, check out the tutorial on [Creating a Remark Transformer Plugin](/tutorial/remark-plugin-tutorial/). + ## What do transformer plugins do? Transformer plugins "transform" data of one type into another type. You'll often use both source plugins and transformer plugins in your Gatsby sites. @@ -286,3 +288,7 @@ const cachedHTML = await cache.get(htmlCacheKey(markdownNode)) cache.set(htmlCacheKey(markdownNode), html) ``` + +## Additional resources + +- Tutorial: [Creating a Remark Transformer Plugin](/tutorial/remark-plugin-tutorial/) diff --git a/docs/docs/creating-and-modifying-pages.md b/docs/docs/creating-and-modifying-pages.md index a0abff99e..a6ad4a3c3 100644 --- a/docs/docs/creating-and-modifying-pages.md +++ b/docs/docs/creating-and-modifying-pages.md @@ -89,10 +89,10 @@ exports.createPages = async ({ graphql, actions, reporter }) => { createPage({ path, component: blogPostTemplate, - // In your blog post template's graphql query, you can use path + // In your blog post template's graphql query, you can use pagePath // as a GraphQL variable to query for data from the markdown file. context: { - path, + pagePath: path, }, }) }) diff --git a/docs/docs/data-fetching.md b/docs/docs/data-fetching.md index 7e310c3b7..1602e7c06 100644 --- a/docs/docs/data-fetching.md +++ b/docs/docs/data-fetching.md @@ -214,6 +214,6 @@ The repo's star count is fetched at runtime; if you refresh the page, this numbe You may be interested in other projects (both used in production and proof-of-concepts) that illustrate this usage: - [Live example](https://gatsby-data-fetching.netlify.com) of the code used in this guide -- [Gatsby store](https://github.com/gatsbyjs/store.gatsbyjs.org): with static product pages at build time and client-side interactions for ecommerce features +- [Gatsby store](https://github.com/gatsbyjs/store.gatsbyjs.org): with static product pages at build time and client-side interactions for e-commerce features - [Gatsby mail](https://github.com/DSchau/gatsby-mail): a client-side email application - [Example repo fetching data using Apollo](https://github.com/jlengstorf/gatsby-with-apollo) diff --git a/docs/docs/data-storage-redux.md b/docs/docs/data-storage-redux.md index a1f89091e..8a9f82e0f 100644 --- a/docs/docs/data-storage-redux.md +++ b/docs/docs/data-storage-redux.md @@ -1,9 +1,8 @@ --- title: Data Storage (Redux) -issue: https://github.com/gatsbyjs/gatsby/issues/21068 --- -This is a stub. Help our community expand it. +During Gatsby's bootstrap & build phases, the state is stored and manipulated using the [Redux](https://redux.js.org/) library. The key purpose of using Redux in Gatsby internals is to centralize all of the state logic. Reviewing the Gatsby [reducers](https://github.com/gatsbyjs/gatsby/tree/master/packages/gatsby/src/redux/reducers) and [actions](https://github.com/gatsbyjs/gatsby/tree/master/packages/gatsby/src/redux/actions) folders gives a comprehensive picture of what state manipulations are possible. Please use the [Gatsby Style Guide](/contributing/gatsby-style-guide/) to ensure your Pull Request gets accepted. diff --git a/docs/docs/deploying-to-cloudflare-workers.md b/docs/docs/deploying-to-cloudflare-workers.md new file mode 100644 index 000000000..54ec3bbfe --- /dev/null +++ b/docs/docs/deploying-to-cloudflare-workers.md @@ -0,0 +1,124 @@ +--- +title: Deploying to Cloudflare Workers +--- + +[Cloudflare Workers](https://workers.cloudflare.com/) is a serverless platform for creating entirely new applications or augmenting existing ones without configuring or maintaining infrastructure. With [Workers Sites](https://developers.cloudflare.com/workers/sites/start-from-existing/) you can deploy any static site including your Gatsby projects to a domain on Cloudflare or for free on your [workers.dev](https://workers.dev) subdomain. + +To enable the KV store required to serve the Gatsby files, you'll need the [Workers Unlimited plan](https://developers.cloudflare.com/workers/about/pricing/) for \$5/month. + +This guide will get you started in a few steps: + +1. Installing wrangler CLI + +Workers Sites requires [wrangler](https://developers.cloudflare.com/workers/tooling/wrangler/). The more straight forward way to install wrangler is with [npm](https://www.npmjs.com/), run the following command: + +```shell +npm i -g @cloudflare/wrangler +``` + +2. Initialize the Project + +To create the Worker code that will serve your Gatsby files, from the root of your Gatsby project run: + +```shell +wrangler init --site +``` + +You'll notice your project structure should now look something like: + +```diff ++ ├── workers-site ++ └── wrangler.toml ++ │   ├── index.js ++ │   ├── package-lock.json ++ │   └── package.json + ├── src + │   ├── components + │   ├── images + │   └── pages + ├── gatsby-config.js + ├── package.json +``` + +3. Configure + +To authenticate into your Cloudflare account run: + +```shell +wrangler config +``` + +Follow the [Quick Start](https://developers.cloudflare.com/workers/quickstart/#configure) for steps on gathering the correct account ID and API token to link wrangler to your Cloudflare account. + +If you don't already have a workers.dev domain run: + +```shell +wrangler subdomain +``` + +Then, add your account ID to the `wrangler.toml` file, and set `bucket` to `"./public"`, which is where Gatsby's built files are output by default: + +```toml +name = "gatsby-project" +type = "webpack" +account_id = "abcd..." +workers_dev = true + +[site] +bucket = "./public" +entry-point = "workers-site" +``` + +This deploys to your workers.dev subdomain. For a custom domain see [Quick Start](https://developers.cloudflare.com/workers/quickstart/#publish-to-your-domain). + +4. Deploy + +You can deploy your application by running the following command in the root of the project directory: + +```shell +wrangler publish +``` + +Now your site is available at gatsby-project.subdomain.workers.dev! + +5. CI with GitHub Actions + +Use wrangler's GitHub action [plugin](https://github.com/cloudflare/wrangler-action) to automatically deploy to Workers every time you push to master. + +Once GitHub Actions is enabled on your repo, add a file to your project's root called `.github/workflows/main.yml` with the contents: + +```yaml +name: Deploy production site + +on: + push: + branches: + - master + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v1 + - name: Navigate to repo + run: cd $GITHUB_WORKSPACE + - uses: actions/setup-node@v1 + with: + node-version: "10.x" + - name: Install deps + run: npm install + - name: Build docs + run: npm run build + - name: Publish + uses: cloudflare/wrangler-action@1.1.0 + with: + apiToken: ${{ secrets.CF_API_TOKEN }} + environment: "production" +``` + +Set up `CF_API_TOKEN` in GitHub secrets with appropriate values from [Quick Start](https://developers.cloudflare.com/workers/quickstart/#configure). + +## Additional resources + +- [Quickstart for Workers Sites](https://developers.cloudflare.com/workers/sites/start-from-existing/) +- [GitHub Action wrangler plugin](https://github.com/cloudflare/wrangler-action) diff --git a/docs/docs/deploying-to-gitlab-pages.md b/docs/docs/deploying-to-gitlab-pages.md index 78b100e05..ea932ba66 100644 --- a/docs/docs/deploying-to-gitlab-pages.md +++ b/docs/docs/deploying-to-gitlab-pages.md @@ -45,6 +45,9 @@ image: node:latest cache: paths: - node_modules/ + # Enables git-lab CI caching. Both .cache and public must be cached, otherwise builds will fail. + - .cache/ + - public/ pages: script: diff --git a/docs/docs/deploying-to-tiiny-host.md b/docs/docs/deploying-to-tiiny-host.md new file mode 100644 index 000000000..dd9b5ae89 --- /dev/null +++ b/docs/docs/deploying-to-tiiny-host.md @@ -0,0 +1,33 @@ +--- +title: Deploying to tiiny.host +--- + +In this guide, you will learn how to deploy your Gatsby site to [tiiny.host](https://tiiny.host). + +[tiiny.host](https://tiiny.host/) is a tool for quickly hosting static websites. + +The tool is perfect for prototyping and sharing your Gatsby site online in a few clicks. + +This guide will show you how to deploy in two steps: + +## Step 1: Prepare your build + +Build your site by running this command in your project's root directory: + +```shell +gatsby build +``` + +This will generate a publishable version of your site in the `./public` folder. + +## Step 2: Deploy + +Zip your `./public` folder and head over to [https://tiiny.host](https://tiiny.host). + +Here, enter a subdomain, upload your zip file and click `Launch`. + +And that's it, you're done! There is no need to register and your site will be live for 7 days or can be extended on the Pro plan. + +## References: + +- [tiiny.host FAQ](https://tiiny.host/help/) diff --git a/docs/docs/environment-variables.md b/docs/docs/environment-variables.md index a12723b40..0d1a7fbab 100644 --- a/docs/docs/environment-variables.md +++ b/docs/docs/environment-variables.md @@ -2,28 +2,28 @@ title: Environment Variables --- -## Environments and Environment Variables - -You can provide environment variables to your site to customise its behavior in different environments. +You can provide environment variables to your site to customize its behavior in different environments. Environment variables can be distinguished between different types. + There are environment variables that are defined in special places intended to be used in different deployment environments. You can call these “Project Env Vars”. + And there are true OS-level environment variables that might be used in command-line calls. You can call these “OS Env Vars”. In both cases you want to be able to access the relevant value of these variables for the environment you are in. -By default gatsby supports only 2 environments: +By default Gatsby supports 2 environments: -- If you run `gatsby develop`, then you will be in the 'development' environment. -- If you run `gatsby build` or `gatsby serve`, then you will be in the 'production' environment. +- **Development.** If you run `gatsby develop`, then you will be in the 'development' environment. +- **Production.** If you run `gatsby build` or `gatsby serve`, then you will be in the 'production' environment. -If you want to define other environments then you'll need to do a little more work. See ["Additional Environments" below](#additional-environments-staging-test-etc). You can also have a look at our [environment variables codesandbox](https://codesandbox.io/s/6w9jjrnnjn) while reading the examples below. +If you want to define other environments then you'll need to do a little more work. See ["Additional Environments" below](#additional-environments-staging-test-etc). You can also have a look at the [environment variables CodeSandbox](https://codesandbox.io/s/6w9jjrnnjn) while reading the examples. ## Accessing Environment Variables in JavaScript All of the Project and OS Env Vars are only directly available at build time, or -when Node.Js is running. They aren't immediately available at run time of the client code; they -need to be actively captured and embedded into our client-side JavaScript. +when Node.js is running. They aren't immediately available at run time of the client code; they +need to be actively captured and embedded into client-side JavaScript. This is achieved during the build using Webpack's [DefinePlugin](https://webpack.js.org/plugins/define-plugin/). Once the environment variables have been embedded into the client-side code, they are accessible from the @@ -39,8 +39,7 @@ or rebuild your site after changing them. For Project Env Vars that you want to access in client-side browser JavaScript, you can define an environment config file, `.env.development` and/or `.env.production`, in your root folder. -Depending on your active environment, the correct one will be found and its values embedded as environment variables in the -browser JavaScript. +Depending on your active environment, the correct one will be found and its values embedded as environment variables in the browser JavaScript. In addition to these Project Environment Variables defined in `.env.*` files, you could also define OS Env Vars. OS Env Vars which are prefixed with `GATSBY_` will become available in @@ -54,7 +53,7 @@ GATSBY_API_URL=https://dev.example.com/api Gatsby runs several Node.js scripts at build time, notably `gatsby-config.js` and `gatsby-node.js`. OS Env Vars will already be available when Node is running, so you can add environment variables the -normal ways e.g. by adding environment variables through your hosting/build tool, your OS, or when +typical ways, e.g. by adding environment variables through your hosting/build tool, your OS, or when calling Gatsby on the command line. In Linux terminals this can be done with: @@ -67,8 +66,8 @@ In Windows it's a little more complex. [Check out this Stack Overflow article fo Project environment variables that you defined in the `.env.*` files will _NOT_ be immediately available in your Node.js scripts. To use those variables, use NPM package [dotenv](https://www.npmjs.com/package/dotenv) to -examine the active `.env.*` file and attached those values, -It's already a dependency of Gatsby, so you can require it in your `gatsby-config.js` or `gatsby-node.js` like this: +examine the active `.env.*` file and attach those values. +`dotenv` is already a dependency of Gatsby, so you can require it in your `gatsby-config.js` or `gatsby-node.js` like this: ```javascript:title=gatsby-config.js require("dotenv").config({ @@ -78,9 +77,9 @@ require("dotenv").config({ Now the variables are available on `process.env` as usual. -## Example +## Example of using an environment variable -Please note that you shouldn't commit `.env.*` files to your source control and rather use options given by your CD provider (e.g. Netlify with its [build environment variables](https://www.netlify.com/docs/continuous-deployment/#build-environment-variables)). +Please note that you shouldn't commit `.env.*` files to your source control and rather use options given by your Continuous Deployment (CD) provider. An example is Netlify with its [build environment variables](https://www.netlify.com/docs/continuous-deployment/#build-environment-variables). ```text:title=.env.development GATSBY_API_URL=https://dev.example.com/api @@ -93,6 +92,7 @@ API_KEY=927349872349798 ``` Note: since Gatsby uses the [Webpack DefinePlugin](https://webpack.js.org/plugins/define-plugin/) to make the environment variables available at runtime, they cannot be destructured from `process.env`; instead, they have to be fully referenced. + `GATSBY_API_URL` will be available to your site (Client-side and server-side) as `process.env.GATSBY_API_URL`.: ```jsx @@ -125,7 +125,7 @@ module.exports = { ## Reserved Environment Variables: > You can not override certain environment variables as some are used internally -> for optimizations during build +> for optimizations during build, such as: - `NODE_ENV` - `PUBLIC_DIR` @@ -136,7 +136,7 @@ Gatsby also allows you to specify another environment variable when running the If set to true, this will expose a `/__refresh` webhook that is able to receive `POST` requests to _refresh_ the sourced content. This exposed webhook can be triggered whenever remote data changes, which means you can update your data without re-launching the development server. -You can trigger this endpoint locally for example on Unix-based operating systems (like Ubuntu and MacOS) you can use `curl -X POST http://localhost:8000/__refresh`. +You can trigger this endpoint locally, for example, on Unix-based operating systems (like Ubuntu and MacOS) using `curl -X POST http://localhost:8000/__refresh`. ## Build Variables @@ -144,18 +144,19 @@ Gatsby uses additional environment variables in the build step to fine-tune the For example, you can set `CI=true` as an environment variable to allow Gatsby's build script to tailor the terminal output to an automated deployment environment. Some CI/CD tooling may already set this environment variable. This is useful for limiting the verbosity of the build output for [dumb terminals](https://en.wikipedia.org/wiki/Computer_terminal#Dumb_terminals), such as terminal in progress animations. -Gatsby detects an optimal level of parallelism for the render phase of `gatsby build` based on the reported number of physical CPUs. For builds that are run in virtual environments, you may need to adjust the number of worker parallelism with the `GATSBY_CPU_COUNT` environment variable. See [Multi-core builds](https://www.gatsbyjs.org/docs/multi-core-builds/). +Gatsby detects an optimal level of parallelism for the render phase of `gatsby build` based on the reported number of physical CPUs. For builds that are run in virtual environments, you may need to adjust the number of worker parallelism with the `GATSBY_CPU_COUNT` environment variable. See [Multi-core builds](/docs/multi-core-builds/). -## Additional Environments (Staging, Test, etc) +## Additional Environments (Staging, Test, etc.) As noted above `NODE_ENV` is a reserved environment variable in Gatsby as it is needed by the build system to make key optimizations when compiling React and other modules. For this reason it is necessary to make use of a secondary environment variable for additional environment support, and manually make the environment variables available to the client-side code. You can define your own OS Env Var to track the active environment, and then to locate the relevant Project Env Vars to load. Gatsby itself will not do anything with that OS Env Var, but you can use it in `gatsby-config.js`. -Specifically, you can use `dotenv` and your individual OS Env Var to locate the `.env.myCustomEnvironment` file, and then use module.exports to store those Project Env Vars somewhere that the client-side JavaScript can access the values (via GraphQL queries). -For instance: if you would like to add a `staging` environment with a custom Google Analytics Tracking ID, and a dedicated `apiUrl`. You can add `.env.staging` at the root of your project with the following modification to your `gatsby-config.js` +Specifically, you can use `dotenv` and your individual OS Env Var to locate the `.env.myCustomEnvironment` file, and then use `module.exports` to store those Project Env Vars somewhere that the client-side JavaScript can access the values (via GraphQL queries). + +### Google Analytics env var example -### Example +If you would like to add a `staging` environment with a custom Google Analytics Tracking ID, and a dedicated `apiUrl` you can add `.env.staging` at the root of your project. In order to do so, use the following modification to your `gatsby-config.js`: ```text:title=.env.staging GA_TRACKING_ID="UA-1234567890" diff --git a/docs/docs/gatsby-image.md b/docs/docs/gatsby-image.md index 826f1e6ed..7ecc44f14 100644 --- a/docs/docs/gatsby-image.md +++ b/docs/docs/gatsby-image.md @@ -183,12 +183,12 @@ export default () => { #### 返り値 - `base64` (string) -- `src` (string) -- `width` (int) -- `height` (int) - `aspectRatio` (float) - `src` (string) - `srcSet` (string) +- `srcSetType` (string) +- `sizes` (string) +- `originalImg` (string) ここでは、クエリーにすべての項目を入力しなくても上記の項目を 1 行ですべて返してくれる `GatsbyImageSharpFluid` のようなフラグメントが便利です。 diff --git a/docs/docs/gatsby-link.md b/docs/docs/gatsby-link.md index f24ca64b4..154e4c907 100644 --- a/docs/docs/gatsby-link.md +++ b/docs/docs/gatsby-link.md @@ -282,7 +282,7 @@ const Form = () => ( It is common to host sites in a sub-directory of a site. Gatsby lets you [set the path prefix for your site](/docs/path-prefix/). After doing so, Gatsby's `` component will automatically handle constructing the correct URL in development and production. -For pathnames you construct manually, there's a helper function, `withPrefix` that prepends your path prefix in production (but doesn't during development where paths don't need prefixed). +For pathnames you construct manually, there's a helper function, `withPrefix` that prepends your path prefix in production (but doesn't during development where paths don't need to be prefixed). ```jsx import { withPrefix } from "gatsby" @@ -389,6 +389,16 @@ onClick = () => { } ``` +## Handling stale client-side pages + +Gatsby's `` component will only fetch each page's resources once. Updates to pages on the site are not reflected in the browser as they are effectively "locked in time". This can have the undesirable impact of different users having different views of the content. + +In order to prevent this staleness, Gatsby requests an additional resource on each new page load: `app-data.json`. This contains a hash generated when the site is built; if anything in the `src` directory changes, the hash will change. During page loads, if Gatsby sees a different hash in the `app-data.json` than the hash it initially retrieved when the site first loaded, the browser will navigate using `window.location`. The browser fetches the new page and starts over again, so any cached resources are lost. + +However, if the page has previously loaded, it will not re-request `app-data.json`. In that case, the hash comparison will not occur and the previously loaded content will be used. + +> **Note:** Any state will be lost during the `window.location` transition. This can have an impact if there is a reliance on state management, e.g. tracking state in [wrapPageElement](/docs/browser-apis/#wrapPageElement) or via a library like Redux. + ## Additional resources - [Authentication tutorial for client-only routes](/tutorial/authentication-tutorial/) diff --git a/docs/docs/gatsby-magic.md b/docs/docs/gatsby-magic.md index 513029e6b..dc9296c59 100644 --- a/docs/docs/gatsby-magic.md +++ b/docs/docs/gatsby-magic.md @@ -46,16 +46,13 @@ Here is where you can find more information on [Routing in Gatsby](/docs/routing ## Redux -Redux is a state management library often used together with React apps. Gatsby is also a React application and uses Redux behind-the-scenes to manage the state of your site. You don’t have to do anything with Redux directly in Gatsby for it to work. +Redux is a state container and is used inside Gatsby to keep its internal state in one place. Redux provides a predictable flow on how and when state updates are done. Gatsby can easily hook into these state transitions to update multiple actions to keep everything consistent. -Redux helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test; that’s why Gatsby uses it as a core technology under the hood. On top of that, Redux provides a great developer experience, such as [live code editing combined with a time-traveling debugger](https://github.com/reduxjs/redux-devtools). Redux is bundled with Gatsby by default to provide automatic state management, and it’s also available as a standalone package on npm. +When you implement a Gatsby [Node API](/docs/node-apis/), you are passed a collection of [actions](/docs/actions/). When using the supplied actions, you are manipulating state that is created, and relied upon, by Gatsby itself such as created pages and webpack config. -In order to use Redux for custom state management in a Gatsby site, you'll need to hook into two of Gatsby's extension points: +Once the build is complete, the work of Redux is done and it is not part of the bundle delivered to the browser unless required independently by the application itself. -- Wrap the root element in your Gatsby markup once using `wrapRootElement`, an API supporting both Gatsby’s server rendering and browser JavaScript processes. -- Create a custom Redux store with reducers and initial state, providing your own state management functionality outside of Gatsby. - -Check out the Using Redux example with [./gatsby-ssr.js](https://github.com/gatsbyjs/gatsby/blob/master/examples/using-redux/gatsby-ssr.js) and [./gatsby-browser.js](https://github.com/gatsbyjs/gatsby/blob/master/examples/using-redux/gatsby-browser.js) files to see how this is implemented. You can also check out more information on the official [Redux](https://redux.js.org/introduction/getting-started) docs. +If using a data store such as Redux in your Gatsby application, check out [Adding a Redux Store](/docs/adding-redux-store). ## GraphQL queries @@ -63,7 +60,7 @@ GraphQL is a query language (the QL part of its name) that Gatsby uses to genera Using a special syntax, you describe the data you want in your component and then that data is given to you, such as site metadata from your `gatsby-config.js`, connected WordPress posts, Markdown files, images, and more. Gatsby uses GraphQL to enable components to declare the data they need and apply it to render on a page. Using GraphQL in Gatsby provides many [benefits](/docs/why-gatsby-uses-graphql/), such as the ability to return data from multiple sources in one query, and transform that data at the same time (such as using Gatsby Image). -Here is how you get started using GraphQL in Gatsby: [https://www.gatsbyjs.org/tutorial/part-four/](/tutorial/part-four/) +Here is how you get started using GraphQL in Gatsby: [/tutorial/part-four/](/tutorial/part-four/) ## webpack @@ -71,7 +68,7 @@ webpack is an open-source JavaScript module bundler that Gatsby uses under the h When Gatsby creates its default webpack config, a function is called allowing you to modify the config using a package called webpack-merge. Gatsby does multiple webpack builds with a somewhat different configuration; each build type is referred to as a “stage”. -You can learn more about [webpack](https://www.gatsbyjs.org/docs/webpack-and-ssr/) including how to [add a custom webpack Config](https://www.gatsbyjs.org/docs/add-custom-webpack-config/) in Gatsby by visiting the docs. +You can learn more about [webpack](/docs/webpack-and-ssr/) including how to [add a custom webpack Config](/docs/add-custom-webpack-config/) in Gatsby by visiting the docs. ## Gatsby Cloud diff --git a/docs/docs/gatsby-project-structure.md b/docs/docs/gatsby-project-structure.md index 3d32c0583..695115600 100644 --- a/docs/docs/gatsby-project-structure.md +++ b/docs/docs/gatsby-project-structure.md @@ -4,7 +4,7 @@ title: Gatsby Project Structure Inside a Gatsby project, you may see some or all of the following folders and files: -``` +```text / |-- /.cache |-- /plugins diff --git a/docs/docs/gatsby-vendor-partnership.md b/docs/docs/gatsby-vendor-partnership.md index 77120e9e5..c500b2ab6 100644 --- a/docs/docs/gatsby-vendor-partnership.md +++ b/docs/docs/gatsby-vendor-partnership.md @@ -54,7 +54,7 @@ Current partners have reported development timelines of 2-3 days when the conten If you have a GraphQL-based API, you **may not need to build an integration at all** -- Gatsby supports integration with GraphQL APIs via so-called ["schema stitching"](/blog/2018-09-25-announcing-graphql-stitching-support/). -If you have questions while building your Gatsby integrations, try reading other supporting documentation such as the [general plugin authoring guide](/docs/creating-plugins/) and [source plugin tutorial](/docs/pixabay-source-plugin-tutorial/). +If you have questions while building your Gatsby integrations, try reading other supporting documentation such as the [general plugin authoring guide](/docs/creating-plugins/) and [source plugin tutorial](/tutorial/pixabay-source-plugin-tutorial/). If you still have questions, please [raise an issue on GitHub](https://github.com/gatsbyjs/gatsby/issues), ask a question in [Discord chat](https://gatsby.dev/discord), or reach out to our team at [developer-relations@gatsbyjs.com](mailto:developer-relations@gatsbyjs.com). diff --git a/docs/docs/glossary.md b/docs/docs/glossary.md index 801c39aa1..403d80aa7 100644 --- a/docs/docs/glossary.md +++ b/docs/docs/glossary.md @@ -6,8 +6,8 @@ disableTableOfContents: true Gatsby をはじめたばかりの時は、覚えるべき用語がたくさんあって大変でしょう。この用語集ではよく使われる用語の意味と、Gatsby のサイト上でどのように使われているかを説明します。 ## A @@ -206,11 +206,11 @@ Linting はコードを解析し、構文エラー等を検出するためのプ ## M -### MDX +### [MDX](/docs/glossary/mdx/) [React](#react) の[コンポーネント](#component)を [Markdown](#markdown) 上でそのまま使用するための拡張機能。 -### Markdown +### [Markdown](/docs/glossary/markdown/) HTML のコンテンツをプレーンテキストで書くための手法です。コンテンツのタイプを特別な文字列を使って表します。例えば、ハッシュ(#)を使って[見出し](https://developer.mozilla.org/ja/docs/Web/HTML/Element/Heading_Elements)を表したり、下線(\_)やアスタリスク(\*)を使ってテキストの強調を表したりします。 @@ -348,6 +348,10 @@ UI とはユーザーインターフェースの事を指します。HCI (Human Gatsby が使用する [JavaScript](#javascript) アプリで、ウェブサイトのコードをバンドルするのに使われます。これは[ビルド時](#build)に自動的に行われます。 +### [WPGraphQL](/docs/glossary/wpgraphql) + +A WordPress plugin that adds [GraphQL](#graphql) capabilities to WordPress. It's another way that you can use WordPress as a content source for Gatsby. + ## X ## Y diff --git a/docs/docs/glossary/build.md b/docs/docs/glossary/build.md new file mode 100644 index 000000000..66ad97ab8 --- /dev/null +++ b/docs/docs/glossary/build.md @@ -0,0 +1,33 @@ +--- +title: Build +disableTableOfContents: true +--- + +Learn what _build_ means and how to set up a build process for your Gatsby project. + +## What is a build? + +_Build_ refers to the process of compiling your site. During a build, or at _build time_, your project gets transformed from component files to optimized HTML, CSS, and JavaScript files that you can [deploy](/docs/glossary#deploy) to your hosting provider. + +There are a few ways to create a build. You can build your site locally on your computer using the [Gatsby CLI](/docs/gatsby-cli/#build), and then deploy changes to your [host](/docs/glossary#hosting). If you use [Gatsby Cloud](https://www.gatsbyjs.com/), you can take advantage of [Gatsby Builds](/blog/2020-01-27-announcing-gatsby-builds-and-reports/), a feature available with every Gatsby Cloud account. You can also use a [continuous deployment](/docs/glossary/continuous-deployment/) service such as [AWS Amplify](/docs/deploying-to-aws-amplify/) or [Netlify](/docs/deploying-to-netlify/). + +For larger teams or larger projects, you may want to use a continuous deployment approach to create builds. Each CD/CI service works slightly differently. Almost all of them, however, use the contents of a Git repository to build your site. + +Gatsby Cloud, for example, integrates with [GitHub](https://github.com/), and a number of hosted [content management systems](/docs/glossary#cms). Gatsby Cloud creates a new build after every commit or content change, although you can also trigger a build manually. + +### Using Gatsby CLI + +For smaller teams and projects, use `gatsby build`. The `gatsby build` command is part of the Gatsby command line interface (or CLI). You'll need to install the CLI interface to create a site with Gatsby. Install it globally using [npm](/docs/glossary/#npm). + +```shell +npm install -g gatsby-cli +``` + +Installing `gatsby-cli` globally makes Gatsby commands available system-wide. You'll use `gatsby new` to [create a new site](/tutorial/part-zero/#create-a-gatsby-site), and `gatsby develop` to start a development server on your local machine. + +When you're ready to publish your project, run the `gatsby build` command to create a production-ready version of your site. Once built, you can use an SFTP client, the [rsync](https://en.wikipedia.org/wiki/Rsync) utility, or similar tool to transfer these files to your host. + +### Learn more about builds + +- [Deploying and Hosting](/docs/deploying-and-hosting/) from the Gatsby docs +- How to enable super fast [Distributed Builds](https://www.gatsbyjs.com/docs/distributed-builds/) for Gatsby Cloud diff --git a/docs/docs/glossary/content-delivery-network.md b/docs/docs/glossary/content-delivery-network.md new file mode 100644 index 000000000..79d154b36 --- /dev/null +++ b/docs/docs/glossary/content-delivery-network.md @@ -0,0 +1,36 @@ +--- +title: Content Delivery Network (CDN) +disableTableOfContents: true +--- + +Learn what a content delivery network or CDN is, how a CDN works, and why you may want to use one for your site. + +## What is a Content Delivery Network (CDN)? + +A Content Delivery Network or CDN is a highly distributed network of servers that speed up the delivery of web content. A CDN copies content from an *origin* and [caches](/docs/glossary/#cache) it on servers around the world. CDN servers put your content closer to your site's visitors, and reduces the time needed to complete a network request. + +Without a content delivery network, a request from Singapore to a server based in New York City has to hop through a network of servers separated by an ocean, and a continent — which can take several seconds. With a content delivery network, a request from Singapore may instead get a response from a CDN server based in Singapore, taking milliseconds. + +By shortening the physical distance between request and response, you reduce the amount of _network latency_. Network latency is the amount of time it takes for a request to travel between computers. Less network latency means that your site loads more quickly, particularly for requests that are farther from the origin. + +> NOTE: For a more complete explanation of how the internet works, watch [_How the Internet Works in 5 Minutes_](https://www.youtube.com/watch?v=7_LPdttKXPc). + +An origin can be a traditional web server, or an object storage service such as [Amazon's S3](/docs/deploying-to-s3-cloudfront/) or [Azure Storage](/blog/2018-11-05-deploying-gatsby-to-azure/). For content created by [static site generators](/docs/glossary/static-site-generator/), such as Gatsby, object storage is a quick and low-cost way to deploy a site to an origin. Object storage also eliminates the need to manage servers. + +A CDN sits between your origin and the DNS servers that direct incoming requests to your site. When the CDN receives a request, it checks to see whether there's a copy of the resource in its cache. If there is, it responds with the cached resource. If there is not, the CDN requests it from the origin and caches the response. Future requests for that resource are then served from the cache. + +Only a fraction of all requests to your website get forwarded to the origin. As a result, your origin uses a fraction of the bandwidth and compute cycles it would use without a CDN. + +In sum, using a content delivery network can: + +- improve your site's performance by reducing network latency; +- improve your site's resiliency by reducing the amount of traffic that reaches your origin server; and +- lower your outgoing transfer costs. + +When used with object storage, you can also forgo the need for traditional servers. + +## Learn more + +- [How the Internet Works in 5 minutes](https://www.youtube.com/watch?v=7_LPdttKXPc) +- [Content delivery network](https://en.wikipedia.org/wiki/Content_delivery_network) from Wikipedia +- [Deploying and Hosting](/docs/deploying-and-hosting/) from the Gatsby docs diff --git a/docs/docs/glossary/continuous-deployment.md b/docs/docs/glossary/continuous-deployment.md index 763d19cde..80a26498e 100644 --- a/docs/docs/glossary/continuous-deployment.md +++ b/docs/docs/glossary/continuous-deployment.md @@ -5,7 +5,7 @@ disableTableOfContents: true ## What is continuous deployment? -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 and releases code automatically, without human intervention. +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 [Zeit](https://zeit.co/) 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. diff --git a/docs/docs/glossary/markdown.md b/docs/docs/glossary/markdown.md new file mode 100644 index 000000000..3b87126d8 --- /dev/null +++ b/docs/docs/glossary/markdown.md @@ -0,0 +1,65 @@ +--- +title: Markdown +disableTableOfContents: true +--- + +Learn what Markdown is, why you might use it, and how it fits into the Gatsby ecosystem. + +## What is Markdown? + +Markdown is a plain text syntax for writing text documents that can be transformed to HTML. Markdown uses punctuation characters to indicate HTML elements. That punctuation then gets converted to HTML tags during a transformation or export process. + +Markdown dates back to 2004, when John Gruber published the original [Markdown syntax guide](https://daringfireball.net/projects/markdown/syntax). Gruber, along with Aaron Swartz, created Markdown with two goals: + +1. to make Markdown as easy-to-read and easy-to-write as is feasible.; and +1. to support inline HTML within Markdown-formatted text. + +Text-to-HTML filters such as [Textile](https://textile-lang.com/) define a syntax that replaces a wide range of HTML elements. Other filters, such as [reStructuredText](https://docutils.readthedocs.io/en/sphinx-docs/user/rst/quickstart.html), do not support inline HTML tags. + +Markdown, by contrast, only defines a syntax for a small subset of HTML elements. For other elements, you use the corresponding HTML tag. In other words, Markdown makes it possible to write documents without knowing HTML, but HTML is available if you need it. A Markdown document might look like the example that follows. + +```markdown +# Markdown! + +You can use Markdown to create documents for [Gatsby](https://www.gatsbyjs.org/). + +
+ +
+ Developers who love using Gatsby versus those who haven't tried it yet. +
+
+``` + +When converted to HTML, the preceding Markdown will become the markup below. + +```html +

Markdown!

+

+ You can use Markdown to create documents for + Gatsby. +

+
+ +
+ Developers who love using Gatsby versus those who haven't tried it yet. +
+
+``` + +You can use Markdown files as a content source for your Gatsby site. To do so, you'll need to install two plugins: [`gatsby-source-filesystem`](/packages/gatsby-source-filesystem) and [`gatsby-transformer-remark`](/packages/gatsby-transformer-remark/). As with Gatsby itself, you can install both using [npm](/docs/glossary/#npm). + +```bash +npm install --save gatsby-source-filesystem gatsby-transformer-remark +``` + +The `gatsby-source-filesystem` plugin reads files from your computer. The `gatsby-transformer-remark` plugin makes the contents of your Markdown files available to GraphQL. + +You can also try a [Gatsby starter](https://www.gatsbyjs.org/starters/?c=Markdown) package that has Markdown support already included. + +## Learn more about Markdown + +- [Markdown syntax](/docs/mdx/markdown-syntax/) from the Gatsby docs +- [CommonMark](https://commonmark.org/), a proposed Markdown specification +- [Sourcing from the Filesystem](/docs/sourcing-from-the-filesystem/) from the Gatsby docs +- [Adding Markdown Pages](/docs/adding-markdown-pages/) from the Gatsby docs diff --git a/docs/docs/glossary/mdx.md b/docs/docs/glossary/mdx.md new file mode 100644 index 000000000..e436b1ac8 --- /dev/null +++ b/docs/docs/glossary/mdx.md @@ -0,0 +1,71 @@ +--- +title: MDX +disableTableOfContents: true +--- + +Learn what MDX is, and how you can use it when creating content for your Gatsby site. + +## What is MDX? + +[MDX](/docs/glossary/#mdx) is an extension to [Markdown](/docs/glossary/markdown/) that lets you include [JSX](/docs/glossary/#jsx) in Markdown documents. MDX makes it possible to include React components in your Gatsby blog posts and pages. + +Markdown defines a plain text syntax for HTML elements such as `h1`, `strong`, and `a`, but still supports inline HTML. An example Markdown document follows. + +```markdown +# Hello world! + +You can use Markdown to create documents for [Gatsby](https://www.gatsbyjs.org/). + +
+ +
MDX adoption has increased 120% since last year.
+
+``` + +MDX takes this one step further, and makes it possible to use JSX in your Markdown documents. Try making the `figure` element into a `Figure` component. + +```jsx +export const Figure = props => { + return ( +
+ +
{props.caption}
+
+ ) +} +``` + +Now you can import this component into your Markdown document. + +```markdown +import { Figure } from './components/Figure'; + +# Hello world! + +You can use Markdown to create documents for [Gatsby](https://www.gatsbyjs.org/). + +
+``` + +If you're creating a Gatsby site from scratch, the [gatsby-starter-mdx-basic](https://github.com/ChristopherBiscardi/gatsby-starter-mdx-basic) is the fastest way to add MDX support. Use the Gatsby [CLI](/docs/glossary/#cli) to create a new project with this starter as a base. + +```shell +gatsby new my-mdx-starter https://github.com/ChristopherBiscardi/gatsby-starter-mdx-basic +``` + +To use MDX with an existing Gatsby site, add the [`gatsby-plugin-mdx`](/packages/gatsby-plugin-mdx/?=gatsby-plugin-mdx) plugin. As with Gatsby itself, you can install it using [npm](/docs/glossary/#npm). You'll also need to install MDX itself, and the React implementation of MDX. + +```shell +npm install --save gatsby-plugin-mdx @mdx-js/mdx @mdx-js/react +``` + +Then add `gatsby-plugin-mdx` to your plugins list in `gatsby-config.js`, and set the [configuration options](/packages/gatsby-plugin-mdx/?=gatsby-plugin-mdx#configuration) you prefer. + +MDX enhances Markdown's capabilities so that you can use React components anywhere in your Gatsby-powered site. + +### Learn more about MDX + +- [MDX](https://mdxjs.com/) official site +- [What is MDX](https://www.youtube.com/watch?v=d2sQiI5NFAM) (video) +- [Adding Components to Markdown with MDX](/docs/mdx/) from the Gatsby docs +- [Introducing JSX](https://reactjs.org/docs/introducing-jsx.html) from the React documentation diff --git a/docs/docs/glossary/server-side-rendering.md b/docs/docs/glossary/server-side-rendering.md new file mode 100644 index 000000000..cec3ebc0e --- /dev/null +++ b/docs/docs/glossary/server-side-rendering.md @@ -0,0 +1,49 @@ +--- +title: Server Side Rendering +disableTableOfContents: true +--- + +Learn what server side rendering is and why it's preferable to client-side (browser) rendering. You'll also learn how Gatsby uses server-side rendering to create static web sites. + +## What is Server-Side rendering? + +_Server-side rendering_ means using a server to generate HTML from JavaScript modules in response to a URL request. That's in contrast to client-side rendering, which uses the browser to create HTML using the DOM. + +Server-side rendering with JavaScript works similarly to other server-side languages such as PHP or .NET, but with [Node.js](/docs/glossary/node/) as the runtime environment. When the server receives a request, it parses the JavaScript modules and data required to generate a response, and returns a rendered HTML page to the browser. + +Single-page applications use client-side rendering. All URL requests are redirected to the same bare-bones HTML document, like the example that follows. + +```html + + + + + + My Single Page App + + + +
+ + + +``` + +Client-side rendering fills in the rest. Views for specific URLs are managed by a JavaScript routing mechanism. Each URL request triggers a DOM update instead of a network request. As a result, sites that use client-side rendering can feel "snappier" and more responsive to user actions. However, client-side rendering has two significant drawbacks. + +1. Site visitors have to wait for the JavaScript bundle to load and for the browser to build the DOM before any content is visible. They may see a blank page or loading image while JavaScript loads. +2. Your bare bones HTML document lacks the keyword, description, and social media metadata (e.g. [OpenGraph](https://ogp.me/)) necessary for search engine optimization and social media sharing. + +Server-side rendering addresses both concerns by creating HTML at _run time_, when the server receives a browser request). Search engines can index your URLs. Visitors can share them on Facebook or Twitter. + +Instead of purely server-side rendering, Gatsby uses the same APIs to create static HTML at [build time](/docs/glossary/build/) when you use `gatsby build`. Gatsby-rendered HTML pages give you the SEO and social sharing advantages of server-side rendering with the speed and security of a [static site generator](/docs/glossary/static-site-generator/). + +### Learn more + +- [Gatsby Server Rendering APIs](/docs/ssr-apis/) + +- [Why server-side render?](/blog/2019-04-02-behind-the-scenes-what-makes-gatsby-great/#why-server-side-render) from _Behind the Scenes: What makes Gatsby Great_ + +- [Search Engine Optimization (SEO) and Social Sharing Cards with Gatsby](/tutorial/seo-and-social-sharing-cards-tutorial/#reach-skip-nav) + +- [What is a Static Site Generator?](/docs/glossary/static-site-generator/#what-is-a-static-site-generator) from the Gatsby docs diff --git a/docs/docs/glossary/static-site-generator.md b/docs/docs/glossary/static-site-generator.md index a9ec3813a..5f1a3c28a 100644 --- a/docs/docs/glossary/static-site-generator.md +++ b/docs/docs/glossary/static-site-generator.md @@ -13,9 +13,9 @@ Static site generators are an alternative to database-driven content management Static site generators, on the other hand, generate HTML pages during a [build](/docs/glossary/#build) process. Gatsby, for example, loads JSON from [GraphQL](/docs/glossary/graphql), and merges that data with components to create HTML pages. These generated pages are then deployed to a web server. When the server receives a request, it responds with rendered HTML. Static pages eliminate the latency that databases introduce. -> Note: It's also possible to use Gatsby [without GraphQL](/using-gatsby-without-graphql/), using the `createPages` API. +> Note: It's also possible to use Gatsby [without GraphQL](/docs/using-gatsby-without-graphql/), using the `createPages` API. -You can also use static site generators to create [JAMStack](/docs/glossary/jamstack.md) sites. JAMStack is a modern web site architecture that uses JavaScript, content APIs, and markup. Gatsby, for example, can use the [WordPress REST API](/sourcing-from-wordpress/) as a data source. +You can also use static site generators to create [JAMStack](/docs/glossary/#jamstack) sites. JAMStack is a modern web site architecture that uses JavaScript, content APIs, and markup. Gatsby, for example, can use the [WordPress REST API](/docs/sourcing-from-wordpress/) as a data source. ### Advantages of static site generators @@ -26,10 +26,10 @@ Static site generators **reduce site complexity**. That, in turn, improves speed - You can use version control software to manage and track changes to your content. - Because your site is static, you can even forgo web servers and load balancers altogether. Instead, you can host your site with a content delivery network that scales with your site's traffic. -There are dozens of static site generators available, created with a range of programming languages. Gatsby is [JavaScript](/glossary#javascript) at its core, and is built with [React](/glossary/react), GraphQL, and [Node.js](/glossary/node/). See how Gatsby [compares to WordPress and Drupal](/features/cms/gatsby-vs-wordpress-vs-drupal) or to popular [static site generators](/features/jamstack/). +There are dozens of static site generators available, created with a range of programming languages. Gatsby is [JavaScript](/docs/glossary/#javascript) at its core, and is built with [React](/docs/glossary/#react), GraphQL, and [Node.js](/docs/glossary/#nodejs). See how Gatsby [compares to WordPress and Drupal](/features/cms/gatsby-vs-wordpress-vs-drupal) or to popular [static site generators](/features/jamstack/). ### Learn more -- [JAMStack](/docs/glossary/jamstack.md) architecture from the Gatsby docs -- [Sourcing Content and Data](/content-and-data/) for Gatsby +- [JAMStack](/docs/glossary/#jamstack) architecture from the Gatsby docs +- [Sourcing Content and Data](/docs/content-and-data/) for Gatsby - [Adding Markdown Pages](/docs/adding-markdown-pages/) from the Gatsby docs diff --git a/docs/docs/glossary/wpgraphql.md b/docs/docs/glossary/wpgraphql.md new file mode 100644 index 000000000..74d9bfdcc --- /dev/null +++ b/docs/docs/glossary/wpgraphql.md @@ -0,0 +1,77 @@ +--- +title: WPGraphQL +disableTableOfContents: true +--- + +Learn what WPGraphQL is and how to use it with Gatsby and WordPress. + +## What is WPGraphQL? + +[WPGraphQL](https://www.wpgraphql.com/) is a WordPress plugin that adds a [GraphQL](/docs/graphql/) API to your WordPress site. [GraphQL](/docs/glossary/graphql/) is a query language for requesting information from an [API](/docs/glossary#api) and a protocol for servers that support it. Gatsby [uses GraphQL](/docs/why-gatsby-uses-graphql/) to serve page data. Adding the WPGraphQL plugin to WordPress lets you use GraphQL to retrieve the specific pieces of content that you need to display on a Gatsby page. + +### Installing WPGraphQL + +You can install WPGraphQL using WordPress' _Add Plugins_ screen. You may also want to install the [WPGraphiQL](https://github.com/wp-graphql/wp-graphiql) plugin. WPGraphiQL turns the [GraphiQL IDE](/docs/running-queries-with-graphiql/) (or integrated development environment) into a WordPress plugin. You do not have to install WPGraphiQL, but it helps you explore data and create queries from WordPress' administration interface. + +1. Download [WPGraphQL](https://github.com/wp-graphql/wp-graphql) and [WPGraphiQL](https://github.com/wp-graphql/wp-graphiql) as ZIP archives from their respective GitHub repositories. +2. Upload `wp-graphql-develop.zip` and `wp-graphiql-master.zip`using the _Upload Plugin_ button on the _Add Plugins_ screen. You'll have to upload and install them one at a time. + +WPGraphQL and WPGraphiQL are also available from the [Packagist](https://packagist.org/) repository. You can install them using [Composer](https://getcomposer.org/), a package manager for PHP. + +```shell +composer require wp-graphql/wp-graphql wp-graphql/wp-graphiql +``` + +After installing WPGraphQL and WPGraphiQL, you'll need to activate them. If you've used the upload method, WordPress will display an _Activate Plugin_ button on the confirmation screen once the installation process completes. You can also activate (or deactivate) WPGraphQL and WPGraphiQL from the _Plugins_ screen. + +Once activated, you may need to update your permalink structure. WPGraphQL requires [pretty permalinks](https://wordpress.org/support/article/using-permalinks/#mod_rewrite-pretty-permalinks), and a custom permalink structure. + +Verify that WPGraphQL is working correctly by visiting the `/graphql` endpoint, relative to your WordPress home URL. If, for example, your WordPress home URL is `https://www.example.com/blog/`, the GraphQL endpoint will be `https://www.example.com/blog/graphql`. + +> **NOTE:** If you are using the `WP_SITEURL` and `WP_HOME` WordPress constants, WPGraphQL will use the value of `WP_HOME`. + +Then you can configure Gatsby to work with your new endpoint. + +### Using WPGraphQL with Gatsby + +You'll need to do two more things before you can use your WordPress-backed GraphQL server with Gatsby: + +1. install the [gatsby-source-graphql](/docs/third-party-graphql/) plugin; and +2. update `gatsby-config.js`. + +Use [npm](/docs/glossary#npm) to install [gatsby-source-graphql](/docs/third-party-graphql/). + +```shell +npm install --save gatsby-source-graphql +``` + +Then update `gatsby-config.js`. Add the plugin to your Gatsby instance. Specify the URL of the GraphQL endpoint and set other [configuration options](/packages/gatsby-source-graphql/). + +```javascript +module.exports = { + plugins: [ + { + resolve: "gatsby-source-graphql", + options: { + // Remote schema query type. This is an arbitrary name. + typeName: "WPGraphQL", + // Field name under which it will be available. Used in your Gatsby query. This is also an arbitrary name. + fieldName: "wpcontent", + // GraphQL endpoint, relative to your WordPress home URL. + url: "https://example.com/blog/graphql", + }, + }, + ], +} +``` + +Be sure to restart the development server after making these changes. Now you can use your WordPress [GraphQL API with Gatsby](/docs/graphql/) just as you would any other GraphQL source. + +WPGraphQL is one way to use Gatsby and WordPress together. It adds a flexible GraphQL API to the robust content management features of WordPress. + +### Learn more about WPGraphQL + +- [WPGraphQL](https://www.wpgraphql.com/) official site +- [Using Gatsby with WPGraphQL](https://www.youtube.com/watch?v=DH7I1xRrbxs) demo by the founder +- [What is GraphQL?](/docs/glossary/graphql/) from the Gatsby docs +- [Why Gatsby Uses GraphQL](/docs/why-gatsby-uses-graphql/) diff --git a/docs/docs/graphql-api.md b/docs/docs/graphql-api.md index 1cc265ead..42fc1d975 100644 --- a/docs/docs/graphql-api.md +++ b/docs/docs/graphql-api.md @@ -3,9 +3,6 @@ title: GraphQL API tableOfContentsDepth: 2 --- -import { GraphqlApiQuery } from "../../www/src/components/api-reference/doc-static-queries" -import APIReference from "../../www/src/components/api-reference" - Gatsby を使う大きな利点は、標準機能としてのデータレイヤーがあり、あなた自身が設定可能な全てのデータソースを含んでいることです。データは[ビルド時](/docs/glossary#build)に集められ、サイト上でデータをどのように処理するかを定義する[スキーマ](/docs/glossary#schema) として組み立てられます。 このページでは Gatsby で使用される GraphQL の特長について、クエリーやデータをソースする方法・サイトごとに合わせた GraphQL カスタマイズ方法などについて説明します。 @@ -227,39 +224,9 @@ GraphQL クエリーは、部分ごとにフラグメントとして再利用で 詳しい内容については、[Gatsby でフラグメントを使う](/docs/using-graphql-fragments/)ガイドをご覧ください。 -### Gatsby フラグメント一覧 - -Gatsby プラグインにもともと含まれているフラグメントもあり、`gatsby-image` や `gatsby-transformer-sharp` により様々なフォーマットで最適化された画像データを返すためのフラグメントや、`gatsby-source-contentful` のデータフラグメントなどがあります。 - -#### Image sharp フラグメント - -以下のフラグメントは `gatsby-transformer-sharp` がインストールされて `gatsby-config.js` に記述されていれば、どのサイトでも使うことができます。 - -これらのフラグメントによるクエリーについては、画像のリサイズや色の変更なども含めて [Gatsby 画像 API ドキュメント](/docs/gatsby-image/)に詳しくまとめられています。 - - - {data => ( - - )} - - -#### コンテントフルフラグメント - -以下のフラグメントは `gatsby-source-contentful` がインストールされ `gatsby-config.js` に記述されていれば、どのサイトでも使うことができます。これらのフラグメントは基本的に `gatsby-transformer-sharp` パッケージ内で記述されたフラグメントを反映します。 - - - {data => ( - - )} - +### Gatsby フラグメント -**注意**: 上記のフラグメントは、公式に管理された Gatsby テンプレートからの引用です。`gatsby-source-datocms` や `gatsby-source-sanity` といった他のプラグインは、そのプラグイン自体のフラグメントも内包しています。そのようなプラグインの一覧は [`gatsby-image` README](/packages/gatsby-image#fragments) で確認できます。 +Gatsby プラグインにもともと含まれているフラグメントもあり、`gatsby-image` や `gatsby-transformer-sharp` により様々なフォーマットで最適化された画像データを返すためのフラグメントや、`gatsby-source-contentful` のデータフラグメントなどがあります。どのプラグインにフラグメントが同梱されているかより詳しく知るには [`gatsby-image` README](/packages/gatsby-image#fragments) を参照してください。 ## さらにカスタマイズする diff --git a/docs/docs/graphql-concepts.md b/docs/docs/graphql-concepts.md index 0da0f774e..b6c05bfcf 100644 --- a/docs/docs/graphql-concepts.md +++ b/docs/docs/graphql-concepts.md @@ -114,14 +114,14 @@ as we do and find it useful for all your projects. When starting out with GraphQL, we recommend the following two tutorials: - https://www.howtographql.com/ -- http://graphql.org/learn/ +- https://graphql.org/learn/ [The official Gatsby tutorial](/tutorial/part-four/) also includes an introduction to using GraphQL specifically with Gatsby. ## How do GraphQL and Gatsby work together? One of the great things about GraphQL is how flexible it is. People use GraphQL -with [many different programming languages](http://graphql.org/code/) and for web and native apps. +with [many different programming languages](https://graphql.org/code/) and for web and native apps. Most people run GraphQL on a server to respond live to requests for data from clients. You define a schema (a schema is a formal way of describing @@ -152,7 +152,7 @@ If you give Gatsby data that looks like this: Gatsby will create a schema that looks something like this: -``` +```text title: String ``` @@ -232,7 +232,7 @@ See also the following blog posts: ### Fragments -Notice that in the above example for [querying images](#images), we used `...GatsbyImageSharpFixed`, which is a GraphQL Fragment, a reusable set of fields for query composition. You can read more about them [here](http://graphql.org/learn/queries/#fragments). +Notice that in the above example for [querying images](#images), we used `...GatsbyImageSharpFixed`, which is a GraphQL Fragment, a reusable set of fields for query composition. You can read more about them [here](https://graphql.org/learn/queries/#fragments). If you wish to define your own fragments for use in your application, you can use named exports to export them in any JavaScript file, and they will be automatically processed by Gatsby for use in your GraphQL queries. @@ -367,7 +367,7 @@ export const query = graphql` ### Getting started with GraphQL -- http://graphql.org/learn/ +- https://graphql.org/learn/ - https://www.howtographql.com/ - https://reactjs.org/blog/2015/05/01/graphql-introduction.html - https://services.github.com/on-demand/graphql/ diff --git a/docs/docs/graphql-reference.md b/docs/docs/graphql-reference.md index d2811e817..1e686d41c 100644 --- a/docs/docs/graphql-reference.md +++ b/docs/docs/graphql-reference.md @@ -14,7 +14,13 @@ For more information, read about [why Gatsby uses GraphQL](/docs/why-gatsby-uses Start with the basics, pulling up the site `title` from your `gatsby-config.js`'s `siteMetadata`. Here the query is on the left and the results are on the right. - + Try editing the query to include the `description` from `siteMetadata`. When typing in the query editor you can use `Ctrl + Space` to see autocomplete options and `Ctrl + Enter` to run the current query. @@ -22,31 +28,60 @@ Try editing the query to include the `description` from `siteMetadata`. When typ Gatsby structures its content as collections of `nodes`, which are connected to each other with `edges`. In this query you ask for the total count of plugins in this Gatsby site, along with specific information about each one. - + Try using the editor's autocomplete (`Ctrl + Space`) to get extended details from the `packageJson` nodes. If you're using Gatsby version `2.2.0` or later, you can remove `edges` and `node` from your query and replace it with `nodes`. The query will still work and the returned object will reflect the `nodes` structure. - + ## Limit There are several ways to reduce the number of results from a query. Here `totalCount` tells you there's 8 results, but `limit` is used to show only the first three. - + ## Skip Skip over a number of results. In this query `skip` is used to omit the first 3 results. - + ## Filter In this query `filter` and the `ne` (not equals) operator is used to show only results that have a title. You can find a good video tutorial on this [here](https://www.youtube.com/watch?v=Lg1bom99uGM). - + Gatsby relies on [Sift](https://www.npmjs.com/package/sift) to enable MongoDB-like query syntax for object filtering. This allows Gatsby to support operators like `eq`, `ne`, `in`, `regex` and querying nested fields through the `__` connector. @@ -58,11 +93,23 @@ filter: { contentType: { in: ["post", "page"] }, draft: { eq: false } } In this query the fields `categories` and `title` are filtered to find the book that has `Fantastic` in its title and belongs to the `magical creatures` category. - + You can also combine the mentioned operators. This query filters on `/History/` for the `regex` operator. The result is `Hogwarts: A History` and `History of Magic`. You can filter out the latter with the `ne` operator. - + ### Complete list of possible operators @@ -80,7 +127,13 @@ _In the playground below the list, there is an example query with a description - `lte`: short for **less than or equal**, must be less than or equal to given value - `elemMatch`: short for **element match**, this indicates that the field you are filtering will return an array of elements, on which you can apply a filter using the previous operators - + If you want to understand more how these filters work, looking at the corresponding [tests](https://github.com/gatsbyjs/gatsby/blob/master/packages/gatsby/src/schema/__tests__/run-query.js) in the codebase could be very useful. @@ -88,17 +141,35 @@ If you want to understand more how these filters work, looking at the correspond The ordering of your results can be specified with `sort`. Here the results are sorted in ascending order of `frontmatter`'s `date` field. - + You can also sort on multiple fields but the `sort` keyword can only be used once. The second sort field gets evaluated when the first field (here: `date`) is identical. The results of the following query are sorted in ascending order of `date` and `title` field. - + `Children's Anthology of Monsters` and `Break with Banshee` both have the same date (`1992-01-02`) but in the first query (only one sort field) the latter comes after the first. The additional sorting on the `title` puts `Break with Banshee` in the right order. By default, sort `fields` will be sorted in ascending order. Optionally, you can specify a sort `order` per field by providing an array of `ASC` (for ascending) or `DESC` (for descending) values. For example, to sort by `frontmatter.date` in ascending order, and additionally by `frontmatter.title` in descending order, you would use `sort: { fields: [frontmatter___date, frontmatter___title], order: [ASC, DESC] }`. Note that if you only provide a single sort `order` value, this will affect the first sort field only, the rest will be sorted in default ascending order. - + ## Format @@ -106,31 +177,61 @@ By default, sort `fields` will be sorted in ascending order. Optionally, you can Dates can be formatted using the `formatString` function. - + Gatsby relies on [Moment.js](https://momentjs.com/) to format the dates. This allows you to use any tokens in your string. See [moment.js documentation](https://momentjs.com/docs/#/displaying/format/) for more tokens. You can also pass in a `locale` to adapt the output to your language. The above query gives you the english output for the weekdays, this example outputs them in german. - + Example: [`anotherDate(formatString: "dddd, MMMM Do YYYY, h:mm:ss a") # Sunday, August 5th 2018, 10:56:14 am`]() Dates also accept the `fromNow` and `difference` function. The former returns a string generated with Moment.js' [`fromNow`](https://momentjs.com/docs/#/displaying/fromnow/) function, the latter returns the difference between the date and current time (using Moment.js' [`difference`](https://momentjs.com/docs/#/displaying/difference/) function). - + ### Excerpt Excerpts accept three options: `pruneLength`, `truncate`, and `format`. `format` can be `PLAIN` or `HTML`. - + ## Sort, filter, limit & format together This query combines sorting, filtering, limiting and formatting together. - + ## Query variables @@ -140,7 +241,13 @@ The query below is the same one as the previous example, but with the input argu To add variables to page component queries, pass these in the `context` object [when creating pages](/docs/creating-and-modifying-pages/#creating-pages-in-gatsby-nodejs). - + ## Group @@ -148,7 +255,13 @@ You can also group values on the basis of a field e.g. the title, date or catego The query below gets you all categories (`fieldValue`) applied to a book and how many books (`totalCount`) a given category is applied to. In addition you are grabbing the `title` of books in a given category. You can see for example that there are 3 books in the `magical creatures` category. - + ## Fragments @@ -156,13 +269,25 @@ Fragments are a way to save frequently used queries for re-use. To create a frag The query below defines a fragment to get the site title, and then uses the fragment to access this information. - + ## Aliasing Want to run two queries on the same datasource? You can do this by aliasing your queries. See the query below for an example: - + When you use your data, you will be able to reference it using the alias instead of the root query name. In this example, that would be `data.someEntries` or `data.someMoreEntries` instead of `data.allMarkdownRemark`. @@ -172,13 +297,25 @@ GraphQL allows you to skip a piece of a query depending on variables. This is ha Try changing variable `withDate` in the example query below: - + Use directive `@include(if: $variable)` to conditionally include a part of a query or `@skip(if: $variable)` to exclude it. You can use those directives on any level of the query and even on fragments. Take a look at an advanced example: - + ## Where next? diff --git a/docs/docs/loading-plugins-from-your-local-plugins-folder.md b/docs/docs/loading-plugins-from-your-local-plugins-folder.md index ac2b3966e..3f5cd0132 100644 --- a/docs/docs/loading-plugins-from-your-local-plugins-folder.md +++ b/docs/docs/loading-plugins-from-your-local-plugins-folder.md @@ -6,7 +6,7 @@ Gatsby can load plugins from your website's local plugins folder, which is a fol Consider this example project structure which includes a local plugin called `gatsby-local-plugin`: -``` +```text /my-gatsby-site └── /src └── /pages @@ -49,7 +49,7 @@ _The [`onPreInit` API](/docs/node-apis/#onPreInit) is the first Node API called Then, when running your site in develop or build mode, you should see "Testing..." logged in your terminal: -```sh +```shell success open and validate gatsby-configs - 0.051s success load plugins - 1.047s Testing... // highlight-line diff --git a/docs/docs/maintaining-a-plugin.md b/docs/docs/maintaining-a-plugin.md index bb05a9dcf..a71bbae3f 100644 --- a/docs/docs/maintaining-a-plugin.md +++ b/docs/docs/maintaining-a-plugin.md @@ -1,10 +1,61 @@ --- title: Maintaining a Plugin -issue: https://github.com/gatsbyjs/gatsby/issues/21067 --- -This is a stub article meant to be filled with tips on how to maintain a Gatsby plugin once you've published it as an npm package. +The Gatsby community thrives on the power of plugins. You often find that there is a plugin for almost everything ranging from source plugins to transformer plugins. A useful way of understanding the purpose of a plugin at a glance is by its name. Check out the [guide to naming conventions for plugins](/docs/naming-a-plugin/) to learn more. -Topics to be covered: +> Wondering how to [create a plugin](/docs/creating-plugins)? Look no further. Start contributing. -- yarn workspaces can solve yarn link inconsistencies +## What is a plugin? + +Gatsby plugins are Node.js packages that implement Gatsby APIs. To learn more take a look at the [plugin documentation](/docs/plugins/). + +In creating plugins, the bulk of the work is during the development phase. However, there’s still a need to take a look at the dependencies and security features from time to time. Keeping plugins up to date can become really tasking and it is important to be careful when updating dependencies, seeing as this could potentially break users' apps. + +However, the consequences of not updating and maintaining a plugin can introduce security issues to your users. The following are some recommendations for maintaining plugins: + +## Handling patches and improvements + +Most plugins generally follow [Semantic Versioning](https://semver.org/) to determine how many releases to do and the type of releases. + +The first public release of a plugin is 0.1.0 or 1.0.0. From there, bugs are fixed in patch releases (e.g. 0.1.1) and features are added or changed in minor releases (e.g. 0.2.0). + +Version 1.0.0 should be released when the plugin's API is considered stable. Version 2.0.0 (and subsequent major releases) would introduce breaking API changes. + +> Consider a version format of X.Y.Z (Major.Minor.Patch). Bug fixes not affecting the API increment the patch version, backwards compatible API additions/changes increment the minor version, and backwards incompatible API changes increment the major version. + +Read more about this concept [in this paper on semantic versioning](https://semver.org/). + +## Update README and document use cases + +Every major version update should also be reflected in the README of the plugin as well as the use case examples. + +It would be great for users to be able to reference several versions of the plugin with the updated examples to see if they want to keep the current version or upgrade and also to understand what the new version offers. Although this is good: + +- Try to not clog your release repository with older versions of the plugin as you update, as they’re not often needed. Instead, simply keep the last few in place. + +- Try not to push every iterative change from Git live + +## Tools for dependency version maintenance + +There are a couple of useful tools that can help with keeping dependencies up to date. + +- [Version Lens](https://marketplace.visualstudio.com/items?itemName=pflannery.vscode-versionlens) enables you to update your dependencies from your `package.json` by allowing you see the available version number the package can be updated to, right above the current version each package in dependencies or devDependencies uses. + +- The [npm check updates](https://www.npmjs.com/package/npm-check-updates) command line tool helps to check for outdated dependencies. You can also use this tool to update those dependencies by following these steps: + +1. Install the tool + +```shell + npm i -g npm-check-updates +``` + +2. Run the command to update dependencies + +```shell +ncu -u +``` + +## Community supporting content and feedback + +Having example repos and support forums on Discord, Twitter or Reddit are great ways to offer community support for your plugin. This would offer a pool of resources for users to get more information on implementations and contribute. diff --git a/docs/docs/mdx/importing-and-using-components.md b/docs/docs/mdx/importing-and-using-components.md index aa39db9c3..25377fe55 100644 --- a/docs/docs/mdx/importing-and-using-components.md +++ b/docs/docs/mdx/importing-and-using-components.md @@ -24,6 +24,11 @@ You can import your own components. **Note**: steps for importing custom components or MDX documents from a relative location in your project are also covered in the [Writing Pages in MDX guide](/docs/mdx/writing-pages/). + + ## Make components available globally as shortcodes To avoid having to import the same component inside of every MDX document you author, you can add components to an `MDXProvider` to make them globally available in MDX pages. This pattern is sometimes referred to as shortcodes. @@ -62,3 +67,54 @@ The Chart is also available since it was passed into the MDXProvider: ``` Because the `` and `` components were passed into the provider, they are available for use in all MDX documents. + + + +## Lazy-loading components + +When you use components in your `.mdx` files, Gatsby will bundle them into the main application bundle. This can cause performance problems. + +In the future, [`gatsby-plugin-mdx`](/packages/gatsby-plugin-mdx) will address this. In the meantime, it can be prudent to lazy-load very large dependencies. The following snippet provides an example for lazy-loading an imaginary `Thing` component: + +```jsx:title=src/components/LazyThing.js +import React from "react" + +const Placeholder = () => null + +const LazyThing = props => { + // While the component is loading, we'll render a fallback placeholder. + // (The Placeholder is a component that renders nothing). + const [Component, setComponent] = React.useState(() => Placeholder) + + // After the initial render, kick off a dynamic import to fetch + // the real component, and set it into our state. + React.useEffect(() => { + import("./Thing.js").then(Thing => setComponent(() => Thing.default)) + }, []) + + return +} + +export default LazyThing +``` + +Inside your MDX, swap out any references to `Thing` with `LazyThing`: + +```diff +-import Thing from "../components/Thing/Thing.js" ++import LazyThing from "../components/Thing/LazyThing.js" + +## Introducing Things + +Here is a demo: + +- ++ +``` + +### Additional resources + +- Follow this detailed [example on using MDX](/examples/using-MDX) to import and render components. diff --git a/docs/docs/mdx/programmatically-creating-pages.md b/docs/docs/mdx/programmatically-creating-pages.md index cc81c367d..c84402cf2 100644 --- a/docs/docs/mdx/programmatically-creating-pages.md +++ b/docs/docs/mdx/programmatically-creating-pages.md @@ -129,8 +129,8 @@ to set up our page. `/blog${value}` is a [template string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) that will result in: -- blog-1.mdx => http://localhost:8000/blog/blog-1/ -- blog-2.mdx => http://localhost:8000/blog/blog-2/ +- `blog-1.mdx` => `http://localhost:8000/blog/blog-1/` +- `blog-2.mdx` => `http://localhost:8000/blog/blog-2/` [`createFilePath`](https://www.gatsbyjs.org/packages/gatsby-source-filesystem/?=gatsby-source#createfilepath) is a function from `gatsby-source-filesystem` that translates file diff --git a/docs/docs/migrating-from-v0-to-v1.md b/docs/docs/migrating-from-v0-to-v1.md index 22f193089..0b33c7a39 100644 --- a/docs/docs/migrating-from-v0-to-v1.md +++ b/docs/docs/migrating-from-v0-to-v1.md @@ -291,7 +291,7 @@ control over what data they got. In v1, templates and pages can query for exactly the data they need. There will be a more in-depth tutorial and GraphQL-specific documentation soon -but in the meantime, check out http://graphql.org/ and play around on Gatsby's +but in the meantime, check out https://graphql.org/ and play around on Gatsby's built-in GraphQL IDE (Graph*i*QL) which can be reached when you start the development server. diff --git a/docs/docs/naming-a-plugin.md b/docs/docs/naming-a-plugin.md index b92a62c96..5e2ca82c4 100644 --- a/docs/docs/naming-a-plugin.md +++ b/docs/docs/naming-a-plugin.md @@ -14,7 +14,7 @@ There are five standard plugin naming conventions for Gatsby: - Docs: [creating a transformer plugin](/docs/creating-a-transformer-plugin/) - **`gatsby-[plugin-name]-*`** — if a plugin is a plugin for another plugin 😅, it should be prefixed with the name of the plugin it extends (e.g. if it adds emoji to the output of `gatsby-transformer-remark`, call it `gatsby-remark-add-emoji`). Use this naming convention whenever your plugin will be included as a plugin in the `options` object of another plugin. - Example: [`gatsby-remark-images`](https://github.com/gatsbyjs/gatsby/tree/master/packages/gatsby-remark-images) - - Docs: [creating a remark plugin](/docs/remark-plugin-tutorial/) + - Docs: [creating a remark plugin](/tutorial/remark-plugin-tutorial/) - **`gatsby-theme-*`** — this naming convention is used for [Gatsby themes](/docs/themes/), which are a type of plugin. This naming convention is used for plugins that own a section, a page, or part of a page on a site or expose files and components for [shadowing](/docs/themes/shadowing/). - Example: [`gatsby-theme-blog`](https://github.com/gatsbyjs/gatsby/tree/master/packages/gatsby-theme-blog) - Docs: [creating a theme](/tutorial/building-a-theme/) diff --git a/docs/docs/overview-of-the-gatsby-build-process.md b/docs/docs/overview-of-the-gatsby-build-process.md index e0c8a9b77..1f94bed1c 100644 --- a/docs/docs/overview-of-the-gatsby-build-process.md +++ b/docs/docs/overview-of-the-gatsby-build-process.md @@ -301,6 +301,8 @@ Page queries that were queued up earlier from query extraction are run so the da With everything ready for the HTML pages in place, HTML is compiled and written out to files so it can be served up statically. Since HTML is being produced in a Node.js server context, [references to browser APIs like `window` can break the build](/docs/debugging-html-builds/) and must be conditionally applied. +By default, Gatsby rebuilds static HTML for all pages on each build. There is an experimental feature flag `GATSBY_EXPERIMENTAL_PAGE_BUILD_ON_DATA_CHANGES` which enables [Page Build Optimizations for Incremental Data Changes](/docs/page-build-optimizations-for-incremental-data-changes/). + ## What do you get from a successful build? When a Gatsby build is successfully completed, everything you need to deploy your site ends up in the `public` folder at the root of the site. The build includes minified files, transformed images, JSON files with information and data for each page, static HTML for each page, and more. diff --git a/docs/docs/page-build-optimizations-for-incremental-data-changes.md b/docs/docs/page-build-optimizations-for-incremental-data-changes.md new file mode 100644 index 000000000..1d93dc8c2 --- /dev/null +++ b/docs/docs/page-build-optimizations-for-incremental-data-changes.md @@ -0,0 +1,63 @@ +--- +title: Experimental Page Build Optimizations for Incremental Data Changes +--- + +Building sites with large amounts of content (10,000s nodes upwards) is relatively fast with Gatsby. However, some projects might start to experience issues when adopting CI/CD principles - continuously building and deploying. Gatsby rebuilds the complete app on each `gatsby build` which means the complete app also needs to be deployed. Doing this each time a small data change occurs unnecessarily increases demand on CPU, memory, and bandwidth. + +One solution to these problems might be to use [Gatsby Cloud's Build features](https://www.gatsbyjs.com/cloud/). + +For projects that require self-hosted environments, where Gatsby Cloud would not be an option, deploying only the content that has changed or is new (incremental data changes, you might say) can help reduce build times, deployment times and demand on resources. + +For more info on the standard build process please see [overview of the gatsby build process](/docs/overview-of-the-gatsby-build-process/) + +## How to use + +To enable this enhancement, use the environment variable `GATSBY_EXPERIMENTAL_PAGE_BUILD_ON_DATA_CHANGES=true` in your `gatsby build` command, for example: + +`GATSBY_EXPERIMENTAL_PAGE_BUILD_ON_DATA_CHANGES=true gatsby build --log-pages` + +This will run the Gatsby build process, but only build pages that have data changes since your last build. If there are any changes to code (JS, CSS) the bundling process returns a new webpack compilation hash which causes all pages to be rebuilt. + +### Reporting what has been built + +You may want to retrieve a list of the pages that were built. For example, if you want to perform a sync action in your CI/CD pipeline. + +To list the paths in the build assets (`public`) folder, you can use one (or both) of the following arguments in your `build` command. + +- `--log-pages` parameter will output all the file paths that were updated or deleted at the end of the build stage. + +```bash +success Building production JavaScript and CSS bundles - 82.198s +success run queries - 82.762s - 4/4 0.05/s +success Building static HTML for pages - 19.386s - 2/2 0.10/s ++ success Delete previous page data - 1.512s +info Done building in 152.084 sec ++ info Built pages: ++ Updated page: /about ++ Updated page: /accounts/example ++ info Deleted pages: ++ Deleted page: /test + +Done in 154.501 sec +``` + +- `--write-to-file` creates two files in the `.cache` folder, with lists of the changed paths in the build assets (`public`) folder. + + - `newPages.txt` will contain a list of new or changed paths + - `deletedPages.txt` will contain a list of deleted paths + +If there are no changed or deleted paths, then the relevant files will not be created in the `.cache` folder. + +## More information + +- This enhancement works by comparing the page data from the previous build to the new page data. This creates a list of page directories that are passed to the static build process. + +- To enable this build option you will need to set an environment variable, which requires access to do so in your build environment. + +- This feature is not available with `gatsby develop`. + +* At the end of each build, gatsby creates a `redux.state` file in `/.cache` that contains previous build data. You will need to persist the `.cache/redux.state` between builds, allowing for comparison. If there is no `redux.state` file located in the `/.cache` folder then a full build will be triggered. + +* Any code or static query changes (templates, components, source handling, new plugins etc) will prompt the creation of a new webpack compilation hash and trigger a full build. + +Note: When using the `GATSBY_EXPERIMENTAL_PAGE_BUILD_ON_DATA_CHANGES` flag it is important to do so consistently when building your project. Otherwise, the cache will be cleared and the necessary data for comparison will no longer be available, removing the ability to check for incremental data changes. diff --git a/docs/docs/plugins-themes-and-starters.md b/docs/docs/plugins-themes-and-starters.md index 35e9161c0..f2589beff 100644 --- a/docs/docs/plugins-themes-and-starters.md +++ b/docs/docs/plugins-themes-and-starters.md @@ -36,3 +36,83 @@ Gatsby offers [official starters](/docs/starters/#official-starters) for a defau - [Starter library](/starters/) - [Creating a starter](/docs/creating-a-starter/) - [Converting a starter to a theme](/docs/themes/converting-a-starter/) + +## Conventions for usage + +Themes are a type of plugin, making both themes and plugins capable of the same functionality. The difference between them is _intended usage_. Themes are intended to own a piece of the site (like an about us page), whereas a plugin is intended to modularize Gatsby APIs into smaller pieces. Themes tend to cover a broader scope of responsibility, packaging up multiple behaviors, where plugins are meant for more specific functionality. + +Starters are generally used as the starting point that plugins and themes are then installed into. However, they're based on one-time use and do not get updated over time as plugins and themes do. + +## Comparing differences + +Once you have a conceptual understanding of what a plugin, theme, and starter is, you may ask yourself what each is suited for in relation to each other. + +The following tables put plugins, themes, and starters side-by-side, showing what each is more appropriate for. + +**Legend** + +| Icon | Feature Capability | +| ---- | ---------------------------------------------------------------- | +| ● | Fully capable (possible and supported) | +| ◐ | Somewhat capable (support is minimal or it is not best practice) | +| ○ | Not capable | + +### Differences and considerations in maintenance + +When it comes to maintaining a Gatsby site, plugins and themes offer a distinct advantage to starters by being distributed as packages. This means making changes in multiple Gatsby sites is as easy as a new install of an updated package upstream. It's difficult to sync changes across multiple sites derived from the same starter. + +| Maintenance | Plugin | Theme | Starter | +| ------------------ | ------ | ----- | ------- | +| Versioning | ● | ● | ◐ | +| Install as Package | ● | ● | ○ | + +#### Versioning + +Starters can still be versioned inside of a repository so that you can track issues or bugs associated with specific updates, but they aren't formally released and published, so they aren't versioned like a plugin or theme is. + +#### Installing as a package + +Starters can't be installed into existing sites, this limitation was one of the motivating factors in developing the newer concept of themes. You can read more about the rationale for themes in the [What are Gatsby Themes guide](/docs/themes/what-are-gatsby-themes/#gatsby-starters). + +### Differences and considerations in configuration + +Plugins and themes can expose options to make them configurable for users. There are different possibilities for configuration like passing in options and shadowing files that make plugins and themes more powerful—but also more complicated—than starters. Because themes are also plugins, shadowing is possible in plugins as well. It may make sense for a plugin to take advantage of the shadowing API, but it is less common. + +| Configuration | Plugin | Theme | Starter | +| --------------------- | ------ | ----- | ------- | +| Pass in Options | ● | ● | ◐ | +| Shadowing | ◐ | ● | ○ | +| Uses Multiple Plugins | ◐ | ● | ● | +| Custom components | ◐ | ● | ● | + +#### Pass in Options + +Plugins and themes both allow options to be passed in when installed in the plugins array of a `gatsby-config`. Starters can be set up with documented options for customization, but there are no officially supported options for starters apart from what the author of the starter decides to write. + +#### Shadowing + +Theme [shadowing](/docs/themes/shadowing/) exists to allow users to override or otherwise extend individual components provided by a theme. For example, a plugin or theme can provide a specific path to `gatsby-config` so the plugin knows where to build pages from, but the user wouldn't be able adjust _how_ those pages are built, only from what path. Theme shadowing allows users to replace a file with their own version of it, allowing them to rewrite that logic to use the path in a different way. + +An example of a plugin that uses shadowing is [`gatsby-plugin-theme-ui`](/packages/gatsby-plugin-theme-ui/?=theme-ui#customizing-the-theme) which allows you to shadow a theme file to use in your own theme. + +Starters aren't capable of shadowing (and they don't need to be), because a user of a starter can adjust any file by editing it directly. + +#### Uses multiple plugins + +Themes are intended to abstract several plugins into one, by making a `gatsby-config` that a Gatsby site will run along with its own config. Starters can also be configured with multiple plugins so someone can get up and running without worrying about configuring too many loose ends. + +#### Custom components + +Custom components are most traditionally distributed as packages in the React ecosystem. Components don't need to hook into the Gatsby build system, so if shipped with a plugin they don't need to be included in a `gatsby-config`'s plugin array. This is the case with `gatsby-image` which is a React component. It doesn't need to be included in the plugins array because it is merely a component. + +Some plugins ship with components you can use in a Gatsby site. An example is the [`` component from `gatsby-plugin-google-analytics`](/packages/gatsby-plugin-google-analytics/?=#outboundlink-component). Other plugins, like [`gatsby-plugin-react-helmet`](/packages/gatsby-plugin-react-helmet), require you to install components from other libraries. + +Themes by convention are more suited to ship with components that could then be shadowed for customization. + +Starters will include components to render data, but they are tied to the starter. + +## Deciding which to use + +As an aid to help try and guide you to which of the 3 options is right for your use case, consider this flowchart: + +![Flowchart walking through options for plugins, starters, and themes](./images/plugin-starter-theme-flowchart.png) 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 4416006fe..2fc7fb1dc 100644 --- a/docs/docs/porting-from-create-react-app-to-gatsby.md +++ b/docs/docs/porting-from-create-react-app-to-gatsby.md @@ -119,11 +119,11 @@ The `gatsby build` command also won't be able to use browser APIs, so some code Some common globals that would need to be protected are: -- `window` -- `localStorage` -- `sessionStorage` -- `navigator` -- `document` +- [`window`](https://developer.mozilla.org/en-US/docs/Web/API/Window) +- [`localStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage) +- [`sessionStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage) +- [`navigator`](https://developer.mozilla.org/en-US/docs/Web/API/Window/navigator) +- [`document`](https://developer.mozilla.org/en-US/docs/Web/API/Document) Additionally, some packages that depend on globals existing (e.g. `react-router-dom`) may need to be [patched](/docs/debugging-html-builds/#fixing-third-party-modules) or migrated to other packages. diff --git a/docs/docs/preparing-for-deployment.md b/docs/docs/preparing-for-deployment.md index 7d1cc7486..eb2d90891 100644 --- a/docs/docs/preparing-for-deployment.md +++ b/docs/docs/preparing-for-deployment.md @@ -48,6 +48,7 @@ gatsby build - [Aerobatic](/docs/deploying-to-aerobatic) - [Heroku](/docs/deploying-to-heroku) - [ZEIT Now](/docs/deploying-to-zeit-now) +- [Cloudflare Workers](/docs/deploying-to-cloudflare-workers) - [GitLab Pages](/docs/deploying-to-gitlab-pages) - [Netlify](/docs/deploying-to-netlify) - [Render](/docs/deploying-to-render) diff --git a/docs/docs/preprocessing-external-images.md b/docs/docs/preprocessing-external-images.md index 863186146..adcbe307c 100644 --- a/docs/docs/preprocessing-external-images.md +++ b/docs/docs/preprocessing-external-images.md @@ -43,6 +43,7 @@ exports.createSchemaCustomization = ({ actions }) => { createTypes(` type MarkdownRemark implements Node { frontmatter: Frontmatter + featuredImg: File @link(from: "featuredImg___NODE") } type Frontmatter { @@ -84,7 +85,7 @@ exports.onCreateNode = async ({ Going step by step through the code: -1. Define some types for `MarkdownRemark` using the Schema Customization API. Defining a field for alternative text as `featuredImgAlt` can also improve accessibility, in addition to providing context for the image if it fails to load. +1. Define some types for `MarkdownRemark` using the Schema Customization API. For `featuredImg`, use the `from` argument to point the `link` extension to the correct field name (with a `___NODE` suffix), [more details about foreign-key fields here](https://www.gatsbyjs.org/docs/schema-customization/#foreign-key-fields). Defining a field for alternative text as `featuredImgAlt` can also improve accessibility, in addition to providing context for the image if it fails to load. 2. Create an `onCreateNode` function so you can watch for when `MarkdownRemark` nodes are made. 3. Use `createRemoteFileNode` by passing in the various required fields and get a reference to the file afterwards. 4. If the Node is created, attach it as a child of the original Node. `___NODE` tells the GraphQL layer that the name before it is going to be a field on the parent Node that links to another Node. To do this, pass the `id` as the reference. Do note, this new node is now attached to the root of the `markdownRemark` node instead of the `frontmatter` field. diff --git a/docs/docs/processing-payments-with-stripe.md b/docs/docs/processing-payments-with-stripe.md index e29db0b15..6fbb6414b 100644 --- a/docs/docs/processing-payments-with-stripe.md +++ b/docs/docs/processing-payments-with-stripe.md @@ -20,83 +20,27 @@ Once logged into the Stripe dashboard, you can find your API keys under the Deve While testing, you must use the key(s) that include the word test. For production code, you will need to use the live keys. As the names imply, your publishable key may be included in code that you share publicly (for example, on the frontend, and in GitHub), whereas your secret key should not be shared with anyone or committed to any public repo. It’s important to restrict access to this secret key because anyone who has it could potentially read or send requests from your Stripe account and see information about charges or purchases or even refund customers. -## Existing plugins and starters using Stripe +## Resources for using Stripe -Several plugins and starters exist to help you get up and running with Stripe. +Several tutorials, plugins and starters exist to help you get up and running with Stripe. + +### Tutorials & Videos + +- [Gatsby E-commerce Tutorial](/tutorial/ecommerce-tutorial): A step-by-step tutorial for adding Stripe Checkout to your Gatsby site. +- [Learn with Jason Episode](https://youtu.be/g4aCBNt5Pcg): Build an E-commerce Site Using Stripe and Gatsby. ### Plugins -- [gatsby-plugin-stripe](https://www.gatsbyjs.org/packages/gatsby-plugin-stripe/) -- [gatsby-source-stripe](https://www.gatsbyjs.org/packages/gatsby-source-stripe/) -- [gatsby-plugin-stripe-checkout](https://www.gatsbyjs.org/packages/gatsby-plugin-stripe-checkout/) +- [gatsby-source-stripe](https://www.gatsbyjs.org/packages/gatsby-source-stripe/): This plugin allows you to bring your product and SKU data into your Gatsby site at build time to be [used with Stripe Checkout](https://www.gatsbyjs.org/tutorial/ecommerce-tutorial/#example-2-import-skus-via-source-plugin). -### Starters +### Starters & Examples +- [Example site from the Gatsby Stripe tutorial](https://github.com/gatsbyjs/gatsby/tree/master/examples/ecommerce-tutorial-with-stripe) - [gatsby-starter-ecommerce](https://www.gatsbyjs.org/starters/parmsang/gatsby-starter-ecommerce/) - [gatsby-starter-stripe](https://www.gatsbyjs.org/starters/brxck/gatsby-starter-stripe/) -## One-time transactions - -Stripe offers two solutions to create payment forms for one-time transactions. According to the Stripe documentation, "Checkout creates a secure, Stripe-hosted payment page that lets you collect payments with just a few lines of code". Stripe Elements is an alternative to Checkout if you need more control of the look and feel of the form. - -### Creating products - -Whether you're using Checkout or Elements, you'll need to create a product on Stripe. The Stripe [Product API](https://stripe.com/docs/api/products/create) can be used to create products, or you can use the dashboard to manually create products. Select Products in the navigation, click `+ New` and fill out the form with your product info. Once you create your product, you'll be able to add SKUs, view the product ID, and more. - -### Checkout - -The [Stripe Checkout documentation](https://stripe.com/docs/payments/checkout/one-time) provides detailed information on how to setup Checkout if you're interested. Because of how Gastby is rendered, there are a few changes you'll need to make like using the `gatsby-plugin-stripe`. - -Check out the [Gatsby E-Commerce Tutorial](https://www.gatsbyjs.org/tutorial/ecommerce-tutorial/#installing-the-stripejs-plugin) to learn how to set up your account to use the "Checkout client-only integration", create products on the Stripe dashboard, and integrate Checkout with Gatsby. The tutorial will explain everything you need to start selling your products. - -### Stripe Elements - -Stripe Elements are prebuilt UI components that help you create checkout flows on the web. Unlike Checkout, Elements give you complete control over the payment experience. Elements require you to write both client-side and server-side code. - -React Stripe Elements is a wrapper around Stripe Elements that help you add Elements to React applications and manage the state and lifecycle of Elements. Documentation can be found at the [React Stripe Elements GitHub](https://github.com/stripe/react-stripe-elements). - -The Stripe documentation explains how to [accept a payment](https://stripe.com/docs/payments/accept-a-payment-charges#node) using Elements. - -As described in the documentation, you'll need to: - -1. Set up Stripe (client-side) -2. Create a payment form with Elements (client-side) -3. Create a token (client-side) -4. Submit the token to your server (client-side) -5. Create a charge with the token (server-side) - -Because of how Gatsby is rendered, you'll need to make sure the window is available before loading Stripe. One way to do this is using the `useState` hook to save an instance of Stripe and the useEffect hook to load Stripe if the window is not undefined. The code snippet below shows a small example of these changes. Instead of passing your API key to the ``, you'll pass the `stripe` variable. - -```javascript -import { Elements, StripeProvider } from "react-stripe-elements" -import CustomForm from "./CustomForm" - -const CheckoutForm = props => { - const [stripe, setStripe] = useState(null) - useEffect(() => { - if (typeof window !== undefined && typeof window.Stripe !== undefined) { - setStripe(window.Stripe("pk_YOUR_PUBLISHABLE_API_KEY")) - } - }, []) - - return ( - - - - - - ) -} -``` - -## Recurring payments - -Stripe Billing is an excellent tool for creating recurring payments, even providing the ability to charge based on usage or tiered subscription plans. The [Billing documentation](https://stripe.com/docs/billing) explains the different options to set up recurring payments. The [Subscription documentation](https://stripe.com/docs/billing/subscriptions/set-up-subscription) shows how to create subscription plans, payment methods, and customers. - ## Other resources - [Stripe website](https://stripe.com/) -- [Stripe API documentation](https://stripe.com/docs/api) -- [Stripe testing documentation](https://stripe.com/docs/testing). -- [React Stripe Elements GitHub](https://github.com/stripe/react-stripe-elements) -- [Making an e-commerce Gatsby Site with Stripe](https://www.gatsbyjs.org/tutorial/ecommerce-tutorial/) +- [Stripe docs](https://stripe.com/docs) +- [Stripe testing docs](https://stripe.com/docs/testing) diff --git a/docs/docs/production-app.md b/docs/docs/production-app.md index 709a60084..53aac29dd 100644 --- a/docs/docs/production-app.md +++ b/docs/docs/production-app.md @@ -21,7 +21,7 @@ The config is quite large, but here are some of the important values in the fina ```javascript { entry: { - app: ".cache/production-app" + app: `.cache/production-app` }, output: { // e.g. app-2e49587d85e03a033f58.js @@ -32,6 +32,7 @@ The config is quite large, but here are some of the important values in the fina publicPath: `/` }, target: `web`, + devtool: `source-map`, mode: `production`, node: { ___filename: true @@ -41,7 +42,37 @@ The config is quite large, but here are some of the important values in the fina // e.g. webpack-runtime-e402cdceeae5fad2aa61.js name: `webpack-runtime` }, - splitChunks: false + splitChunks: { + chunks: `all`, + cacheGroups: { + // disable Webpack's default cacheGroup + default: false, + // disable Webpack's default vendor cacheGroup + vendors: false, + // Create a framework bundle that contains React libraries + // They hardly change so we bundle them together to improve + framework: {}, + // Big modules that are over 160kb are moved to their own file to + // optimize browser parsing & execution + lib: {}, + // All libraries that are used on all pages are moved into a common chunk + commons: {}, + // When a module is used more than once we create a shared bundle to save user's bandwidth + shared: {}, + // All CSS is bundled into one stylesheet + styles: {} + }, + // Keep maximum initial requests to 25 + maxInitialRequests: 25, + // A chunk should be at least 20kb before using splitChunks + minSize: 20000 + }, + minimizers: [ + // Minify javascript using Terser (https://terser.org/) + plugins.minifyJs(), + // Minify CSS by using cssnano (https://cssnano.co/) + plugins.minifyCss(), + ] } plugins: [ // A custom webpack plugin that implements logic to write out chunk-map.json and webpack.stats.json @@ -52,6 +83,8 @@ The config is quite large, but here are some of the important values in the fina There's a lot going on here. And this is just a sample of the output that doesn't include the loaders, rules, etc. We won't go over everything here, but most of it is geared towards proper code splitting of your application. +The splitChunks section is the most complex part of the Gatsby webpack config as it configures how Gatsby generates the most optimized bundles for your website. This is referred to as Granular Chunks as Gatsby tries to make the generated JavaScript files as granular as possible by deduplicating all modules. You can read more about [SplitChunks](https://webpack.js.org/plugins/split-chunks-plugin/#optimizationsplitchunks) and [chunks](https://webpack.js.org/concepts/under-the-hood/#chunks) on the [official webpack website](https://webpack.js.org/). + Once Webpack has finished compilation, it will have produced a few key types of bundles: ##### app-[contenthash].js @@ -62,6 +95,14 @@ This bundle is produced from [production-app.js](https://github.com/gatsbyjs/gat This contains the small [webpack-runtime](https://webpack.js.org/concepts/manifest/#runtime) as a separate bundle (configured in `optimization` section). In practice, the app and webpack-runtime are always needed together. +##### framework-[contenthash].js + +The framework bundle contains the React framework. Based on user behavior, React hardly gets upgraded to a newer version. Creating a separate bundle improves users' browser cache hit rate as this bundle is likely not going to be updated often. + +##### commons-[contenthash].js + +Libraries used on every Gatsby page are bundled into the commons javascript file. By bundling these together, you can make sure your users only need to download this bundle once. + ##### component---[name]-[contenthash].js This is a separate bundle for each page. The mechanics for how these are split off from the main production app are covered in [Code Splitting](/docs/how-code-splitting-works/). @@ -89,7 +130,7 @@ To show how `production-app` works, let's imagine that you've just refreshed the */ ``` -Then, the app, webpack-runtime, component, and data json bundles are loaded via `` and ` +const stripe = await loadStripe("pk_test_TYooMQauvdEDq54NiTphI7jx") ``` これにより、Stripe の[不正検出](https://stripe.com/docs/stripe-js/reference#including-stripejs)]が容易になります @@ -159,6 +158,7 @@ Stripe ダッシュボードでテスト SKU と本番 SKU の両方を作成す ```jsx:title=src/components/checkout.js import React from "react" +import { loadStripe } from "@stripe/stripe-js" const buttonStyles = { fontSize: "13px", @@ -180,29 +180,26 @@ const Checkout = class extends React.Component { this.stripe = window.Stripe("pk_test_jG9s3XMdSjZF9Kdm5g59zlYd") } - async redirectToCheckout(event) { - event.preventDefault() - const { error } = await this.stripe.redirectToCheckout({ - items: [{ sku: "sku_DjQJN2HJ1kkvI3", quantity: 1 }], - successUrl: `http://localhost:8000/page-2/`, - cancelUrl: `http://localhost:8000/`, - }) +const redirectToCheckout = async event => { + event.preventDefault() + const stripe = await stripePromise + const { error } = await stripe.redirectToCheckout({ + items: [{ sku: "sku_DjQJN2HJ1kkvI3", quantity: 1 }], + successUrl: `http://localhost:8000/page-2/`, + cancelUrl: `http://localhost:8000/`, + }) - if (error) { - console.warn("Error:", error) - } + if (error) { + console.warn("Error:", error) } +} - render() { - return ( - - ) - } +const Checkout = () => { + return ( + + ) } export default Checkout @@ -213,41 +210,35 @@ export default Checkout React をインポートし、いくつかの style のボタンを追加し、React 関数を導入しました。`componentDidMount()`や、`redirectToCheckout()` といった関数は Stripe の機能の中で最も重要です。`componentDidMount()` 関数はコンポーネントが最初に DOM にマウントされた時に起動する React のライフサイクルメソッドであり、Stripe.js クライアントを初期化するのに適した場所です。コードは以下のようになります。 ```jsx:title=src/components/checkout.js - componentDidMount() { - this.stripe = window.Stripe("pk_test_jG9s3XMdSjZF9Kdm5g59zlYd") - } +const stripePromise = loadStripe("pk_test_jG9s3XMdSjZF9Kdm5g59zlYd") ``` これによって Stripe プラットフォームが識別され、製品とセキュリティの設定に対して支払いリクエストが検証され、Stripe アカウントの支払いが処理されます。 ```jsx:title=src/components/checkout.js - async redirectToCheckout(event) { - event.preventDefault() - const { error } = await this.stripe.redirectToCheckout({ - items: [{ sku: "sku_DjQJN2HJ1kkvI3", quantity: 1 }], - successUrl: `http://localhost:8000/page-2/`, - cancelUrl: `http://localhost:8000/`, - }) +const redirectToCheckout = async event => { + event.preventDefault() + const stripe = await stripePromise + const { error } = await stripe.redirectToCheckout({ + items: [{ sku: "sku_DjQJN2HJ1kkvI3", quantity: 1 }], + successUrl: `http://localhost:8000/page-2/`, + cancelUrl: `http://localhost:8000/`, + }) - if (error) { - console.warn("Error:", error) - } + if (error) { + console.warn("Error:", error) } +} ``` `redirectToCheckout()` 関数は支払いのリクエストを検証し、Stripe がホストする支払いページにリダイレクトするか、エラーオブジェクトで解決します。`successUrl` と `cancelUrl` を適切な URL に置き換えてください。 ```jsx:title=src/components/checkout.js - render() { - return ( - - ) - } +return ( + +) ``` `render()` 関数は style をボタンに適用し、`redirectToCheckout()` 関数をボタンの onclick イベントにバインドします。 @@ -302,17 +293,16 @@ npm install gatsby-source-stripe ```js:title=gatsby-config.js module.exports = { siteMetadata: { - title: `Gatsby e-commerce Starter`, + title: `Gatsby E-commerce Starter`, }, plugins: [ `gatsby-plugin-react-helmet`, - "gatsby-plugin-stripe", { resolve: `gatsby-source-stripe`, options: { objects: ["Sku"], secretKey: process.env.STRIPE_SECRET_KEY, - downloadFiles: true, + downloadFiles: false, }, }, ], @@ -447,13 +437,14 @@ const formatPrice = (amount, currency) => { return numberFormat.format(price) } -const SkuCard = class extends React.Component { - async redirectToCheckout(event, sku, quantity = 1) { +const SkuCard = ({ sku, stripePromise }) => { + const redirectToCheckout = async (event, sku, quantity = 1) => { event.preventDefault() - const { error } = await this.props.stripe.redirectToCheckout({ + const stripe = await stripePromise + const { error } = await stripe.redirectToCheckout({ items: [{ sku, quantity }], - successUrl: `http://localhost:8000/page-2/`, - cancelUrl: `http://localhost:8000/advanced`, + successUrl: `${window.location.origin}/page-2/`, + cancelUrl: `${window.location.origin}/advanced`, }) if (error) { @@ -485,9 +476,10 @@ export default SkuCard 最後に、`Skus` コンポーネントをリファクタリングして Stripe.js クライアントを初期化し、`props` で Stripe.js クライアントを伝えながら `SkuCards` をレンダリングする必要があります。 ```jsx:title=src/components/Products/Skus.js -import React, { Component } from "react" +import React from "react" import { graphql, StaticQuery } from "gatsby" -import SkuCard from "./SkuCard" // highlight-line +import SkuCard from "./SkuCard" +import { loadStripe } from "@stripe/stripe-js" const containerStyles = { display: "flex", @@ -497,50 +489,36 @@ const containerStyles = { padding: "1rem 0 1rem 0", } -class Skus extends Component { - // Initialise Stripe.js with your publishable key. - // You can find your key in the Dashboard: - // https://dashboard.stripe.com/account/apikeys - // highlight-start - state = { - stripe: null, - } - - componentDidMount() { - const stripe = window.Stripe(process.env.GATSBY_STRIPE_PUBLIC_KEY) - this.setState({ stripe }) - } - // highlight-end - - render() { - return ( - { + return ( + ( -
- {skus.edges.map(({ node: sku }) => ( - {/* highlight-line */} - ))} -
- )} - /> - ) - } + } + `} + render={({ skus }) => ( +
+ {skus.edges.map(({ node: sku }) => ( + + ))} +
+ )} + /> + ) } export default Skus diff --git a/docs/docs/pixabay-source-plugin-tutorial.md b/docs/tutorial/pixabay-source-plugin-tutorial.md similarity index 99% rename from docs/docs/pixabay-source-plugin-tutorial.md rename to docs/tutorial/pixabay-source-plugin-tutorial.md index 56e8567d3..d751e83ee 100644 --- a/docs/docs/pixabay-source-plugin-tutorial.md +++ b/docs/tutorial/pixabay-source-plugin-tutorial.md @@ -1,9 +1,7 @@ --- -title: Pixabay Image Source Plugin Tutorial +title: "Creating an Image Source Plugin" --- -Creating your own source plugin. - ## What this tutorial covers In this tutorial you'll create your own source plugin. Your plugin will source data from [pixabay.com](https://pixabay.com) allowing you to add Pixabay images to any Gatsby site. diff --git a/docs/tutorial/plugin-and-theme-tutorials.md b/docs/tutorial/plugin-and-theme-tutorials.md new file mode 100644 index 000000000..4fb119dd5 --- /dev/null +++ b/docs/tutorial/plugin-and-theme-tutorials.md @@ -0,0 +1,13 @@ +--- +title: Plugin & Theme Tutorials +--- + +**Gatsby plugins** are Node.js packages that implement Gatsby APIs and are commonly installed through a registry like npm. Common use cases for Gatsby plugins include data sourcing and hooking into lifecycle methods. + +**Gatsby themes** are a type of plugin that includes a `gatsby-config.js` file and adds pre-configured functionality, data sourcing, and/or UI code to Gatsby sites. Themes might pre-bundle plugins and configure them so users don't have to, providing a nice abstraction that can be installed and updated as a package. + +To learn more about plugins and themes in general, you may be interested to check out the docs guides on [plugins](/docs/plugins/) and [themes](/docs/themes/). + +For a deeper understanding of the differences between plugins, themes, and starters, you can also refer to the related [conceptual guide](/docs/plugins-themes-and-starters/). + + diff --git a/docs/docs/remark-plugin-tutorial.md b/docs/tutorial/remark-plugin-tutorial.md similarity index 99% rename from docs/docs/remark-plugin-tutorial.md rename to docs/tutorial/remark-plugin-tutorial.md index 1639cf4a6..6c5655348 100644 --- a/docs/docs/remark-plugin-tutorial.md +++ b/docs/tutorial/remark-plugin-tutorial.md @@ -1,5 +1,5 @@ --- -title: Remark Plugin Tutorial +title: "Creating a Remark Transformer Plugin" --- [`gatsby-transformer-remark`](/packages/gatsby-transformer-remark) empowers developers to translate Markdown into HTML to be consumed via Gatsby's GraphQL API. Blogs and other content based sites can highly benefit from functionality enabled with this plugin. With this plugin, authors of content for the site don't need to worry about how the site is written or structured but can rather focus on writing engaging posts and content! diff --git a/docs/tutorial/seo-and-social-sharing-cards-tutorial/index.md b/docs/tutorial/seo-and-social-sharing-cards-tutorial/index.md new file mode 100644 index 000000000..607f026a7 --- /dev/null +++ b/docs/tutorial/seo-and-social-sharing-cards-tutorial/index.md @@ -0,0 +1,640 @@ +--- +title: Search Engine Optimization (SEO) and Social Sharing Cards with Gatsby +--- + +Perhaps you've been approached by an SEO _expert_ who can maximize your revenue and page views just by following these **Three Simple Tricks**! Relatively few people make the concerted effort to implement SEO in their web app. This tutorial will share some of the ins and outs of SEO and how you can implement common SEO patterns in your Gatsby web app, today. By the end of this post you'll know how to do the following: + +- Implement SEO patterns with [react-helmet][react-helmet] +- Create an optimized social sharing card for Twitter, Facebook, and Slack +- Tweak the SEO component exposed in the default gatsby starter ([`gatsby-starter-default`][gatsby-starter-default]) + +## Implementation + +A core ingredient for SEO is a meaningful `title` tag. Make sure to include related keywords without falling into buzzword bingo. Some crawlers also respect `meta` tags, while Google seems to ignore these tags for ranking and indexing at all. + +You probably have seen something like the following: + +```html +My Wonderful App + + +``` + +The _bare minimum_ requirement is to include a `title` tag for basic SEO. However, the following describes a powerful combo of content rendered at _build time_ powered by Gatsby and GraphQL. + +## Gatsby + GraphQL + +GraphQL is a crucial feature enabled via Gatsby (note: you don't [_have_ to use GraphQL with Gatsby][unstructured-data]). Leveraging GraphQL to query your indexable content--wherever it lives (at build time!)--is one of the most powerful and flexible techniques enabled via Gatsby. The following sections are a brief look at the implementation of an extensible and flexible SEO component. + +### `StaticQuery` + +Gatsby distinguishes between page-level queries and component queries. The former can use page GraphQL queries while the latter can use [`StaticQuery`][gatsby-static-query]. A StaticQuery will be parsed, evaluated, and injected at _build time_ into the component that is requesting the data, allowing to fall back to sane defaults, while also providing an extensible, reusable component. + +### Creating the SEO component + +Using the power and flexibility of React, you can create a React component to power this functionality. + +> Note: `react-helmet` is enabled, by default, in gatsby-starter-default and gatsby-starter-blog. +> +> If you're not using those starters, [follow this guide for installation instructions][gatsby-plugin-react-helmet] + +```jsx:title=src/components/seo.js +import React from "react" +// highlight-start +import Helmet from "react-helmet" +import { useStaticQuery, graphql } from "gatsby" +// highlight-end + +function SEO({ description }) { + const { site } = useStaticQuery( + graphql` + query { + # highlight-start + site { + siteMetadata { + title + description + author + keywords + siteUrl + } + } + # highlight-end + } + ` + ) + + const metaDescription = description || site.siteMetadata.description + + return null +} + +export default SEO +``` + +This component doesn't _do_ anything yet, but it's the foundation for a useful, extensible component. It leverages the `useStaticQuery` functionality enabled via Gatsby to query siteMetadata (e.g. details in `gatsby-config.js`) with description and keywords. At this point, the `SEO` component returns `null` to render nothing. Next, you will _actually_ render something and build out the prototype for this SEO component. + +```jsx:title=src/components/seo.js +import React from "react" +import Helmet from "react-helmet" +import { useStaticQuery, graphql } from "gatsby" + +function SEO({ description, lang, meta }) { + const { site } = useStaticQuery( + graphql` + query { + site { + siteMetadata { + title + description + author + keywords + siteUrl + } + } + } + ` + ) + + const metaDescription = description || site.siteMetadata.description + + return ( + + ) +} + +// highlight-start +SEO.defaultProps = { + lang: `en`, + meta: [], + description: ``, +} +// highlight-end + +export default SEO +``` + +Whew, getting closer! This will now render the `meta` `description` tag, and will do so using content injected at build-time with the `useStaticQuery` hook. Additionally, it will add the `lang="en"` attribute to the root-level `html` tag to silence that pesky Lighthouse warning 😉. + +This is still the bare bones, rudimentary approach to SEO. An additional step is to enhance this functionality and get some useful functionality for sharing a page via social networks like Facebook, Twitter, and Slack. + +### Implementing social SEO + +In addition to SEO for actual _search_ engines you also want those pretty cards that social networks like Twitter and Slack enable. Specifically, the implementation should feature: + +- Description for embedded results +- Title for embedded results +- (Optionally) display an image and a card if an image is passed in to the component + +```jsx:title=src/components/seo.js +import React from "react" +import PropTypes from "prop-types" // highlight-line +import Helmet from "react-helmet" +import { useStaticQuery, graphql } from "gatsby" + +// highlight-next-line +function SEO({ description, lang, meta, image: metaImage, title }) { + const { site } = useStaticQuery( + graphql` + query { + site { + siteMetadata { + title + description + author + keywords + siteUrl + } + } + } + ` + ) + + const metaDescription = description || site.siteMetadata.description + // highlight-start + const image = + metaImage && metaImage.src + ? `${data.site.siteMetadata.siteUrl}${metaImage.src}` + : null + // highlight-end + + return ( + + ) +} + +SEO.defaultProps = { + lang: `en`, + meta: [], + description: ``, +} + +SEO.propTypes = { + description: PropTypes.string, + lang: PropTypes.string, + meta: PropTypes.arrayOf(PropTypes.object), + title: PropTypes.string.isRequired, + // highlight-start + image: PropTypes.shape({ + src: PropTypes.string.isRequired, + height: PropTypes.number.isRequired, + width: PropTypes.number.isRequired, + }), + // highlight-end +} + +export default SEO +``` + +Woo hoo! You enabled not only SEO for search engines like Google and Bing, but you also laid the groundwork for enhanced sharing capabilities on social networks. Finally, you will learn to add support for one of the more useful functionalities for SEO: a canonical link. + +## `link rel="canonical"` + +A canonical link is a hint to a search engine that this is the _source_ for this content. It helps resolve duplicate content issues. For instance, if you have several paths to the same content, you can use a canonical link as akin to a soft redirect which will **not** harm your search ranking if implemented correctly. + +To implement this functionality, you need to do the following: + +1. Enable passing a `pathname` prop to your SEO component +1. Prefix your `pathname` prop with your `siteUrl` (from `gatsby-config.js`) + - A canonical link should be _absolute_ (e.g. `https://your-site.com/canonical-link`), so you will need to prefix with this `siteUrl` +1. Tie into the `link` prop of `react-helmet` to create a `` tag + +```jsx:title=src/components/seo.js +import React from "react" +import PropTypes from "prop-types" +import Helmet from "react-helmet" +import { useStaticQuery, graphql } from "gatsby" + +// highlight-next-line +function SEO({ description, lang, meta, image: metaImage, title, pathname }) { + const { site } = useStaticQuery( + graphql` + query { + site { + siteMetadata { + title + description + author + keywords + siteUrl + } + } + } + ` + ) + + const metaDescription = description || site.siteMetadata.description + const image = + metaImage && metaImage.src + ? `${data.site.siteMetadata.siteUrl}${metaImage.src}` + : null + // highlight-start + const canonical = pathname + ? `${data.site.siteMetadata.siteUrl}${pathname}` + : null + // highlight-end + + return ( + + ) +} + +SEO.defaultProps = { + lang: `en`, + meta: [], + description: ``, +} + +SEO.propTypes = { + description: PropTypes.string, + lang: PropTypes.string, + meta: PropTypes.arrayOf(PropTypes.object), + title: PropTypes.string.isRequired, + image: PropTypes.shape({ + src: PropTypes.string.isRequired, + height: PropTypes.number.isRequired, + width: PropTypes.number.isRequired, + }), + // highlight-next-line + pathname: PropTypes.string, +} + +export default SEO +``` + +Woo hoo! Lots to digest here, but you've enabled adding an _absolute_ canonical link by passing in a `pathname` prop and prefixing with `siteUrl`. + +To bring it all home, it's time to begin actually _using_ this extensible SEO component to show all of these moving parts coming together to deliver a great SEO experience. + +## Using the SEO component + +You created an extensible SEO component. It takes a `title` prop and then (optionally) `description`, `meta`, `image`, and `pathname` props. + +### In a page component + +```jsx:title=src/pages/index.js +import React from "react" + +import Layout from "../components/layout" +import SEO from "../components/seo" // highlight-line + +function Index() { + return ( + + {/* highlight-line */} +

lol - pretend this is meaningful content

+
+ ) +} + +export default Index +``` + +### In a template + +In many cases, you want to build a Markdown powered blog (see: [this tutorial][gatsby-markdown-blog] for more info). Of course, you want some nice SEO as well as a nifty image for sharing on Twitter, Facebook, and Slack. The following steps are needed: + +- Create a Markdown post +- Add an image, and add it to the Markdown posts frontmatter +- Query this image with GraphQL + +#### Creating the post + +```shell +mkdir -p content/blog/2019-01-04-hello-world-seo +touch content/blog/2019-01-04-hello-world-seo/index.md +``` + +```markdown:title=content/blog/2019-01-04-hello-world-seo/index.md +--- +date: 2019-01-04 +featured: images/featured.jpg +--- + +Hello World! +``` + +#### Adding the image + +Let's see how an attached image will look like. For this tutorial, you can use the following image: + +![Scribble stones forming SEO](./images/seo.jpg) + +The image will need to be located at `content/blog/2019-01-04-hello-world-seo/images/featured.jpg`. + +Make sure to use appropriately sized images for social sharing. Facebook and Twitter have restrictions beyond which they will simply ignore your image. + +#### Querying with GraphQL + +```jsx:title=src/templates/blog-post.js +import React from "react" +import { Link, graphql } from "gatsby" + +import Bio from "../components/bio" +import Layout from "../components/layout" +import SEO from "../components/seo" // highlight-line +import { rhythm, scale } from "../utils/typography" + +class BlogPostTemplate extends React.Component { + render() { + const post = this.props.data.markdownRemark + const siteTitle = this.props.data.site.siteMetadata.title + const image = post.frontmatter.image + ? post.frontmatter.image.childImageSharp.resize + : null // highlight-line + + return ( + + {/* highlight-start */} + + {/* highlight-end */} +

{post.frontmatter.title}

+
+ + ) + } +} + +export default BlogPostTemplate + +export const pageQuery = graphql` + # highlight-start + query BlogPostBySlug($slug: String!) { + site { + siteMetadata { + title + author + } + } + markdownRemark(fields: { slug: { eq: $slug } }) { + id + excerpt(pruneLength: 160) + html + frontmatter { + title + description + image: featured { + childImageSharp { + resize(width: 1200) { + src + height + width + } + } + } + } + } + } + # highlight-end +` +``` + +There are a few aspects worth nothing here: + +- You're using `pruneLength: 160` for the excerpt; this is because [SEO meta descriptions should be between 150-170 characters][seo-description-length] + +- This is a slick feature of Gatsby's GraphQL capabilities, and will truncate (e.g. with a trailing `...`) appropriately. Perfect! + +- The image query is intentionally simplified, but a good base to build upon. There are specific size and aspect ratio requirements for [both Facebook][facebook-og-image] and [Twitter][twitter-image]. + +## The Payoff + +Using the techniques outlined in this post, you've made your Gatsby application SEO-friendly as well as sharable on common social networks. Check out the following examples of a sample blog post. + +### Google + +![Indexing Results by Google](./images/google.png) + +### Facebook + +![Social Sharing Card as on Facebook](./images/facebook.png) + +### Twitter + +![Social Sharing Card as on Twitter](./images/twitter.png) + +### Slack + +![Social Sharing Card as on Slack](./images/slack.png) + +To learn more about these validations, check out how to _validate_ SEO with the following tools from [Google][google-validation], [Twitter][twitter-validation], and [Facebook][facebook-validation]. + +The SEO resources outlined in this tutorial aren't _only_ a best practice, they're also a best practice enabled, by default. Available **today** in `gatsby-starter-default`, use: + +```shell +npm gatsby new my-new-gatsby-app +``` + +and you'll have the `SEO` component available to maximize your SEO and social sharing capabilities. Check it out! + +## Further Learning + +This tutorial is merely a shallow dive into the depths of SEO. Consider it a primer for further learning and a gentle introduction to some SEO concepts with a Gatsby twist. To truly master these concepts is outside the scope of this tutorial, but it truly is fascinating stuff that can directly lead to more eyes on your content! + +### References + +- Facebook uses the [Open Graph][og] tag format +- Twitter uses `twitter:` keywords. See [Twitter Cards][twitter-cards] for more info +- Slack reads tags in the following order ([source][slack-unfurl]) + 1. oEmbed server + 1. Twitter cards tags / Facebook Open Graph tags + 1. HTML meta tags +- Both [Google][google-json-ld] and [Apple][apple-json-ld] offer support for JSON-LD, which is _not covered_ in this guide + - If you'd like to learn more, check out [this excellent guide](https://nystudio107.com/blog/json-ld-structured-data-and-erotica) for more info on JSON-LD +- Check out the [`gatsby-seo-example`][gatsby-seo-example] for a ready-to-use starter for powering your Markdown-based blog. + +[gatsby-starter-default]: https://github.com/gatsbyjs/gatsby-starter-default +[gatsby-static-query]: /docs/static-query/ +[gatsby-markdown-blog]: /docs/adding-markdown-pages/ +[gatsby-plugin-react-helmet]: /packages/gatsby-plugin-react-helmet/ +[react-helmet]: https://github.com/nfl/react-helmet +[unstructured-data]: /docs/using-gatsby-without-graphql/ +[og]: https://developers.facebook.com/docs/sharing/webmasters/#markup +[twitter-cards]: https://developer.twitter.com/en/docs/tweets/optimize-with-cards/overview/abouts-cards.html +[seo-description-length]: https://yoast.com/shorter-meta-descriptions/ +[facebook-og-image]: https://developers.facebook.com/docs/sharing/best-practices#images +[twitter-image]: https://developer.twitter.com/en/docs/tweets/optimize-with-cards/overview/summary-card-with-large-image.html +[slack-unfurl]: https://medium.com/slack-developer-blog/everything-you-ever-wanted-to-know-about-unfurling-but-were-afraid-to-ask-or-how-to-make-your-e64b4bb9254 +[google-validation]: https://support.google.com/webmasters/answer/6066468?hl=en +[twitter-validation]: https://cards-dev.twitter.com/validator +[facebook-validation]: https://developers.facebook.com/tools/debug/sharing +[gatsby-seo-example]: https://github.com/DSchau/gatsby-seo-example +[google-json-ld]: https://developers.google.com/search/docs/guides/intro-structured-data +[apple-json-ld]: https://developer.apple.com/library/archive/releasenotes/General/WhatsNewIniOS/Articles/iOS10.html#//apple_ref/doc/uid/TP40017084-DontLinkElementID_2 diff --git a/docs/tutorial/theme-tutorials.md b/docs/tutorial/theme-tutorials.md deleted file mode 100644 index 3be97e002..000000000 --- a/docs/tutorial/theme-tutorials.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: テーマの利用 ---- - -Gatsby テーマは Gatsby の機能をカプセル化、再利用、構成するための新しい方法です。 - -この章では、下記についてのチュートリアルを扱います。 - -1. 単一のテーマ(ブログテーマ)を用いてサイトを立ち上げる。 -2. 複数のテーマ(ブログテーマとメモテーマ)を組み合わせたサイトを立ち上げる。 - -テーマ全般についてもっと詳しく知りたい方は、[ドキュメント内のテーマの章](/docs/themes)もご参照ください。 - -