diff --git a/docs/docs/why-gatsby-uses-graphql.md b/docs/docs/why-gatsby-uses-graphql.md index f578392ec..9d1fbb59f 100644 --- a/docs/docs/why-gatsby-uses-graphql.md +++ b/docs/docs/why-gatsby-uses-graphql.md @@ -1,23 +1,23 @@ --- -title: Why Gatsby Uses GraphQL +title: Gatsby が GraphQL を使用する理由 --- -A common question about Gatsby is, “Why does Gatsby use GraphQL? Doesn’t it generate static files?” +「なぜ Gatsby は GraphQL を使用するのですか?Gatsby は静的ファイルを生成するのですよね?」とよく質問されます。 -Without providing some context, it can seem like GraphQL is overkill for something like Gatsby. In this document, you’ll see what problems arise when creating pages, and how those problems can be solved using GraphQL. +何らかのコンテキストが与えられなければ、Gatsby にとって GraphQL は過剰に見えるかもしれません。このドキュメントでは、ページ作成時に発生する問題と、それらの問題を GraphQL を使用して解決する方法について説明します。 -## Create a page without any data +## データなしでページを作成する -For any kind of pages that aren’t directly created in `src/pages/`, you’ll need Gatsby’s [`createPages` Node API](/docs/node-apis/#createPages) to create pages programmatically. +`src/pages/` 以外の場所でページを動的に作成するためには、Gatsby の [`createPages` Node API](/docs/node-apis/#createPages) が必要です。 -All that’s required to create a page is a `path` where it should be created and the component that should be rendered there. +`path` とレンダリングしたいコンポーネントを指定するだけで、ページを作成できます。 -For example, if you had the following component: +例えば、次のコンポーネントを考えてみましょう。 ```jsx:title=src/templates/no-data.js import React from "react" @@ -34,7 +34,7 @@ const NoData = () => ( export default NoData ``` -You could programmatically create a page at `/no-data/` by adding the following to `gatsby-node.js`: +以下のコードを `gatsby-node.js` に追加することで、`/no-data/` にページを動的に作成できます。 ```js:title=gatsby-node.js exports.createPages = ({ actions: { createPage } }) => { @@ -45,22 +45,22 @@ exports.createPages = ({ actions: { createPage } }) => { } ``` -After running `gatsby develop`, you’ll see the following at `http://localhost:8000/no-data/`: +`gatsby develop` コマンドを実行すると、`http://localhost:8000/no-data/` では次のように表示されます。 -![Screenshot of the page generated by the previous code snippet.](./images/why-gql-no-data.png) +![1つ前のコードスニペットで生成されたページのスクリーンショット](./images/why-gql-no-data.png) -In the simplest cases, this is all that’s required for building pages with Gatsby. However, you’ll often want to pass data to the page so that the template component is reusable. +もっともシンプルな場合は、Gatsby でページを作成するために必要な手順はこれだけです。しかし多くの場合は、ページにデータを渡し、テンプレートコンポーネントを再利用できるようにしたいはずです。 -## Create a page with hard-coded data +## ハードコードされたデータでページを作成する -To pass data to the created pages, you’ll need to pass `context` to the `createPage` call. +作成されたページにデータを渡すには、`context` を `createPage` に渡す必要があります。 -In `gatsby-node.js`, you can add context like so: +`gatsby-node.js` では、以下のように `context` を追加できます。 ```js:title=gatsby-node.js exports.createPages = ({ actions: { createPage } }) => { @@ -75,11 +75,11 @@ exports.createPages = ({ actions: { createPage } }) => { } ``` -The `context` property accepts an object, and you can pass in any data you want the page to be able to access. +このようにして追加された `context` は、オブジェクトを受け取ります。`context` に渡された任意のデータは、そのページから参照できるようにできます。 -> **NOTE:** There are a few reserved names that _cannot_ be used in `context`. They are: `path`, `matchPath`, `component`, `componentChunkName`, `pluginCreator___NODE`, and `pluginCreatorId`. +> **ヒント:** `context` の中で使用できない予約語がいくつかあります。 それらは、`path` 、`matchPath` 、`component` 、`componentChunkName` 、`pluginCreator___NODE` 、そして `pluginCreatorId` です。 -When Gatsby creates pages, it includes a prop called `pageContext` and sets its value to `context`, so you can access any of the values in your component: +Gatsby が作成したページには `pageContext` というプロパティが含まれており、その値は `context` となっています。そのため、作成されたページからは、コンポーネントの任意の値を参照できます。 ```jsx:title=src/templates/with-context.js import React from "react" @@ -94,22 +94,22 @@ const WithContext = ({ pageContext }) => ( export default WithContext ``` -Start the development server with `gatsby develop` and visit `http://localhost:8000/page-with-context/` to see the created page: +`gatsby develop` コマンドで開発サーバーを起動し、`http://localhost:8000/page-with-context/` にアクセスして、作成されたページを確認してみましょう。 -![Screenshot of a page with hard-coded context.](./images/why-gql-with-context.png) +![ハードコードされたデータで作成されたページのスクリーンショット](./images/why-gql-with-context.png) -In some cases, this approach may be enough. However, it’s often necessary to create pages from data that can't be hard-coded. +場合によっては、この方法で十分かもしれません。しかし、ハードコードできないデータからページを作成したい場合も多々あります。 -## Create pages from JSON with images +## 画像を含む JSON ファイルからページを作成する -In many cases, the data for pages can't feasibly be hard-coded into `gatsby-node.js`. More likely it will come from an external source, such as a third-party API, local Markdown, or JSON files. +多くの場合、ページ用のデータを `gatsby-node.js` にハードコーディングすることはできません。 サードパーティー API 、ローカル Markdown、JSON ファイルなどの外部ソースからデータを取得する可能性が高くなるでしょう。 -For example, you might have a JSON file with post data: +例えば、投稿データを含む JSON ファイルがあるとします。 ```json:title=data/products.json [ @@ -137,9 +137,9 @@ For example, you might have a JSON file with post data: ] ``` -The images need to be added to the `/static/images/` folder. (This is where things start to get hard to manage — the JSON and the images aren’t in the same place.) +この場合、画像を `/static/images/` フォルダーに追加する必要があります。(JSON ファイルと画像が同じ場所に追加されないため、これらの管理は難しくなります) -Once the JSON and the images are added, you can create product pages by importing the JSON into `gatsby-node.js` and loop through the entries to create pages: +JSON ファイルと画像を追加したら、JSON ファイルを `gatsby-node.js` にインポートしてエントリーをループ処理し、 product ページを作成します。 ```js:title=gatsby-node.js exports.createPages = ({ actions: { createPage } }) => { @@ -159,7 +159,7 @@ exports.createPages = ({ actions: { createPage } }) => { } ``` -The product template still uses `pageContext` to display the product data: +product テンプレートは、引き続き `pageContext` を使用して product データを表示します。 ```jsx:title=src/templates/product.js import React from "react" @@ -180,55 +180,55 @@ const Product = ({ pageContext }) => ( export default Product ``` -Run `gatsby develop`, then open `http://localhost:8000/product/space-socks/` to see one of the generated products. +`gatsby develop` コマンドを実行し、`localhost:8000/product/space-socks/` を開いて、生成された product の一例を見てみましょう。 -![Screenshot of a rendered product page.](./images/why-gql-product-json.png) +![レンダリングされた product ページのスクリーンショット](./images/why-gql-product-json.png) -This gets the job done, but it has a few shortcomings that are going to get more complicated as time goes on: +以上で作業は完了ですが、時間が経つにつれて複雑になる欠点がいくつかあります。 -1. The images and the product data are in different places in the source code. -2. The image paths are absolute from the _built_ site, not the source code, which makes it confusing to know how to find them from the JSON. -3. The images are unoptimized, and any optimization you do would have to be manual. -4. To create a preview listing of all products, we’d need to pass _all_ of the product info in `context`, which will get unwieldy as the number of products increases. -5. It’s not very obvious where data is coming from in the templates that render the pages, so updating the data might be confusing later. +1. 画像と product データは、ソースコードの異なる場所にあります。 +2. 画像のパスは、ソースコードではなく*ビルドされた*サイトからの絶対パスであるため、JSON ファイルから画像のパスを見つける方法を知るのは大変です。 +3. 画像は最適化されていないため、手動で最適化を行う必要があります。 +4. すべての product のプレビューリストを作成するには、`context` に _全ての_ product の情報を渡す必要があります。`context` は、product の数が増えるにつれて扱いにくくなります。 +5. ページをレンダリングするテンプレートのどの部分からデータが来ているかがあまり明らかではないため、データを更新すると後で混乱を招く可能性があります。 -To overcome these limitations, Gatsby introduces GraphQL as a data management layer. +これらの欠点を克服するために、Gatsby はデータ管理層として GraphQL を使用しています。 -## Create pages using GraphQL +## GraphQL を使用してページを作成する -There’s a bit more up-front setup required to get data into GraphQL, but the benefits far outweigh the cost. +GraphQL にデータを取り込むには、少し前もってセットアップする必要がありますが、その利益はコストをはるかに上回ります。 -Using `data/products.json` as an example, by using GraphQL we’re able to solve all of the limitations from the previous section: +`data/products.json` を例に考えてみましょう。GraphQL を使用することにより、前のセクションで述べた全ての欠点を解決できます。 -1. The images can be collocated with the products in `data/images/`. -2. Image paths in `data/products.json` can be relative to the JSON file. -3. Gatsby can automatically optimize images for faster loading and better user experience. -4. You no longer need to pass all product data into `context` when creating pages. -5. Data is loaded using GraphQL in the components where it’s used, making it much easier to see where data comes from and how to change it. +1. 画像は `data/images/` にある product と同じ場所に配置できます。 +2. `data/products.json` 中に記述される画像のパスを、その JSON ファイルを起点とする相対パスにできます。 +3. Gatsby は、画像読み込みの高速化と UX の向上のために、画像を自動的に最適化できます。 +4. ページを作成するときに、すべての product データを `context` に渡す必要がなくなりました。 +5. データは使用されているコンポーネント内で GraphQL を用いて読み込まれるため、私たちはそのデータの取得元と変更方法をとても簡単に確認できます。 -### Add the necessary plugins to load data into GraphQL +### GraphQL にデータを読み込むために必要なプラグインを追加する -In order to load the product and image data into GraphQL, you need to add a few [Gatsby plugins](/plugins/). Namely, you need plugins to: +product データと画像を GraphQL に読み込むには、以下の [Gatsby プラグイン](/plugins/)を追加し、いくつかの手順を踏む必要があります。 -- Load the JSON file into Gatsby’s internal data store, which can be queried using GraphQL ([`gatsby-source-filesystem`](/packages/gatsby-source-filesystem/)) -- Convert JSON files into a format you can query with GraphQL ([`gatsby-transformer-json`](/packages/gatsby-transformer-json/)) -- Optimize images ([`gatsby-plugin-sharp`](/packages/gatsby-plugin-sharp/)) -- Add data about optimized images to Gatsby’s data store ([`gatsby-transformer-sharp`](/packages/gatsby-transformer-sharp/)) +- JSON ファイルを Gatsby の内部データストアに読み込みます。このデータストアでは、GraphQL を使用してクエリーを実行できます。([`gatsby-source-filesystem`](/packages/gatsby-source-filesystem/)) +- GraphQL を使用してクエリーを実行できるように、JSON ファイルのフォーマットを変換します。([`gatsby-transformer-json`](/packages/gatsby-transformer-json/)) +- 画像を最適化します。([`gatsby-plugin-sharp`](/packages/gatsby-plugin-sharp/)) +- 最適化された画像に関するデータを Gatsby のデータストアに追加します。([`gatsby-transformer-sharp`](/packages/gatsby-transformer-sharp/)) -In addition to the plugins, we’ll use [`gatsby-image`](/packages/gatsby-image/) to display the optimized images with lazy loading. +以上のプラグインに加えて、[`gatsby-image`](/packages/gatsby-image/) を使用し、最適化された画像を遅延読み込みで表示します。 -Install these packages using the command line: +次のコマンドラインを使用し、これらのパッケージをインストールします。 ```shell npm install --save gatsby-source-filesystem gatsby-transformer-json gatsby-plugin-sharp gatsby-transformer-sharp gatsby-image ``` -Then add them to `gatsby-config.js`: +次に、これらを `gatsby-config.js` に追加します。 ```js:title=gatsby-config.js module.exports = { @@ -246,21 +246,21 @@ module.exports = { } ``` -To check that this worked, you can use the GraphQL Playground, which is available during development, by running: +これが機能したことを確認するために、GraphQL Playground で次のコマンドを実行してみましょう。 ```shell GATSBY_GRAPHQL_IDE=playground gatsby develop ``` -> **NOTE:** The `GATSBY_GRAPHQL_IDE=playground` part of this command is optional. Adding it enables the GraphQL Playground instead of GraphiQL, which is an older interface for exploring GraphQL. +> **ヒント:** このコマンドのうち、 `GATSBY_GRAPHQL_IDE=playground` 部分はオプションです。 このオプションを追加すると、GraphQL を探索するための古いインターフェースである GraphiQL の代わりに GraphQL Playground を有効にできます。 -You can explore the available data schema using the “Docs” tab at the right. +右側の「ドキュメント」タブを使えば、利用可能なデータスキーマを確認できます。 -One of the available options is `allProductsJson`, which contains “edges”, and those contain “nodes”. +利用可能なオプションの 1 つは `allProductsJson` で、これにはいくつかのノードを持つエッジが含まれます。 -The JSON transformer plugin has created one node for each product, and inside the node you can select the data you need for that product. +JSON ファイル変換プラグインは product ごとに 1 つのノードを作成します。ノード内ではその product に必要なデータを選択できます。 -You can write a query to select each product’s slug like this: +各 product のスラッグを選択するクエリーは以下のように記述できます。 ```graphql { @@ -274,20 +274,20 @@ You can write a query to select each product’s slug like this: } ``` -Test this query by entering it into the left-hand panel of the GraphQL Playground, then pressing the play button in the top center. +GraphQL Playground の左側のパネルにこのクエリーを入力して上部中央の実行ボタンを押し、テストしてみましょう。 -The results will appear in the panel between the query and the docs, and they’ll look like this: +次のような実行結果がクエリーとドキュメントの間のパネルに表示されるはずです。 ![GraphQL Playground](./images/why-gql-playground.png) -### Generate pages with GraphQL +### GraphQL でページを生成する -In `gatsby-node.js`, you can use the GraphQL query you just wrote to generate pages. +`gatsby-node.js` では、先ほど書いた GraphQL クエリーを使用してページを生成できます。 ```js:title=gatsby-node.js exports.createPages = async ({ actions: { createPage }, graphql }) => { @@ -317,15 +317,15 @@ exports.createPages = async ({ actions: { createPage }, graphql }) => { } ``` -You need to use the `graphql` helper that’s available to the [`createPages` Node API](/docs/node-apis/#createPages) to execute the query. To make sure that the result of the query comes back before continuing, use [`async`/`await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). +このクエリを実行するには、[`createPages` Node API](/docs/node-apis/#createPages) で利用できる `graphql` ヘルパーを使用する必要があります。続行する前にクエリーの結果が返されることを確認するには、[`async`/`await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) を使用してください。 -The results that come back are very similar to the contents of `data/products.json`, so you can loop through the results and create a page for each. +返される結果は `data/products.json` の内容にとても似ているため、その結果をループ処理して各ページを作成できます。 -However, note that you’re only passing the `slug` in `context` — you’ll use this in the template component to load more product data. +ただし、`context` には `slug` のみを渡すことに気をつけてください。この `slug` をテンプレートコンポーネントで使用すれば、より多くの product データを読み込むことができます。 -As you’ve already seen, the `context` argument is made available to the template component in the `pageContext` prop. To make queries more powerful, Gatsby _also_ exposes everything in `context` as a GraphQL variable, which means you can write a query that says, in plain English, “Load data for the product with the slug passed in `context`.” +今まで見てきたように、引数 `context` は、プロパティ `pageContext` のテンプレートコンポーネントで使用できるようになります。また、クエリーをより強力にするため、Gatsby は `context` のすべての情報を GraphQL の変数として使用できるようにしています。つまり、「product と `context` に渡されたスラッグを一緒に読み込んで!」というクエリーを書くことができるのです。 -Here’s what that looks like in practice: +実際のクエリーは次のようになります。 ```jsx:title=src/templates/product-graphql.js import React from "react" @@ -369,19 +369,19 @@ const Product = ({ data }) => { export default Product ``` -A few notes about this file: +このファイルに関して、以下のことに気をつけてください。 -1. The result of the query is added to the template component as the `data` prop. -2. The image path was automatically converted by the Sharp transformer into a “child node” that includes optimized versions of the image. -3. The query uses a [GraphQL fragment](/packages/gatsby-image/#fragments) to query all the required data for optimized images. GraphQL fragments _do not work_ in the GraphQL Playground. -4. The `img` tag has been swapped out for a `gatsby-image` component named `Image`. Instead of a `src` attribute, it accepts an object with optimized image data. +1. クエリーの結果は、`data` プロパティとしてテンプレートコンポーネントに追加されます。 +2. 画像パスは、Sharp トランスフォーマーによって、最適化された画像を含む「子ノード」に自動的に変換されました。 +3. [GraphQL フラグメント](/packages/gatsby-image/#fragments) を使用して、最適化された画像を作成するために必要なすべてのデータを指定したクエリーを作成します。なお、GraphQL Playground では GraphQL フラグメントは動作しません。 +4. `img` タグは、`Image` という名前の `gatsby-image` コンポーネントと交換されました。`src` 属性の代わりに、最適化された画像データを持つオブジェクトを受け入れます。 -Save this file, run `gatsby develop`, then open `http://localhost:8000/gql/purple-hat/`: +このファイルを保存し、`gatsby develop` コマンドを実行して、`http://localhost:8000/gql/purple-hat/` を開いてみましょう。 -![Lazy loaded image of an angry cat wearing the purple hat.](./images/why-gql-images.gif) +![紫色の帽子をかぶった猫の遅延読み込み画像](./images/why-gql-images.gif) -The image is now optimized and lazy loaded. +これで画像は最適化され、遅延読み込みされました。 -After the initial setup, loading data with GraphQL is fairly similar to directly loading JSON, but it provides extra benefits like automatically optimizing images and keeping the data loading in the same place where it’s used. +初期設定後、GraphQL を使用したデータの読み込みは、JSON ファイルからの直接読み込みとかなり似ています。しかし、画像を自動的に最適化し、使用される場所と同じ場所にデータを読み込めるなど、さらなる利点があります。 -GraphQL is certainly not required, but the benefits of adopting GraphQL are significant. GraphQL will simplify the process of building and optimizing your pages, so it’s considered a best practice for structuring and writing Gatsby applications. +GraphQL は確かに必須ではありません。しかし、GraphQL を使用することの利益は大きいです。 GraphQL は、ページの構築と最適化のプロセスを簡素化するため、Gatsby アプリケーションの構築と作成のベストプラクティスと言えるでしょう。