LoginSignup
9
7

More than 5 years have passed since last update.

Gatsby メモ

Last updated at Posted at 2018-10-13

この本最高なので読んでます。
https://mottox2.booth.pm/items/1044224

読みながら、細々メモ。書籍の方はもっと丁寧かつ、概要等も説明しているので、そちらを買ってください。

# cli がアップデートされていたので一旦アンインストール
npm uninstall gatsby-cli -g
npm install gatsby-cli -g
cd プロジェクトを作成したいパス
gatsby new uncle-javascript # プロジェクト名を uncle-javascript に指定

webstorm プロジェクトを開く
npm run develop -> localhost:8000 で立ち上がる

pages/index.js が example.com に相当するページ
pages/page-3.js を作れば、ルーティングしなくても example.com/page-3/ にルーティングされる

link をさせる

import { Link } from 'gatsby'
<Link to="/page-3/">Go to page 3</Link>

styled-components を使う
shell
npm install --save gatsby-plugin-styled-components styled-components babel-plugin-styled-components

plugin を追加したら gatsby-config に追記して読み込ます
plugins の配列に 'gatsby-plugin-styled-componets' を追記

styledComponents のこつ

// これが本体
import styled from 'styled-components'
// さっき読み込んだやつで、Header というコンポーネントを作る
// styled.要素名
// `` の間に CSS を書く
const Header = styled.h1`
  color: red
`
const IndexPage = () => (
    <Header>JavaScript-uncle.com</Header>
)
import { css } from 'styled-components'

// css そのものを書く系
export const test = css`
  color: red
`

// 単に文字列
export const colors = {
 black: '#000'
}

---
import styled from 'styled-components'
import { test, colors } from '/上のファイル'

const Test = styled.h1`
  width: 200px;
  ${test} // css の一つしてガット入る
  color: ${colors.black} // 単に文字列を展開
`

Build => npm run build

Github にソース全体をプッシュ
Netlify でそのリポジトリを指定
勝手にビルドしてデプロイしてくれる
ドメインも買える
Github にプッシュしたら、勝手にデプロイしてくれる

graphql

import React from 'react'
import { graphql } from 'gatsby' // これで query を書いてデータを取得する

import Layout from '../components/layout'

// おそらく props.data として graphql の結果が帰ってくるので、
// プロパティを直に data として展開
const ThirdPage = ({ data }) => (
  <Layout>
    <h1>graphql</h1>
    <p>
      {data.site.siteMetadata.title} {data.site.siteMetadata.description}
    </p>
  </Layout>
)

// query という名前で export すると、
// 勝手にこのファイルのコンポーネントの props に data としてぶっこまれる模様
export const query = graphql`
  query {
    site {
      siteMetadata {
        title
        description
      }
    }
  }
`

// query します
// site = おそらくサイト内にあるファイルを参照する
// siteMetadata = gatsby-config.js の sitemetadata
// title と description を参照

export default ThirdPage

開発時に出る localhost/__qraphiql みたいなところから、GUI でクエリを試せる画面にいける。

module.css

test.module.css
.test {
    background: red;
}
import React from 'react'
import { Link } from 'gatsby'
import styled from 'styled-components'

import Layout from '../components/layout'

// module.css を読み込む
import testStyles from '../components/test.module.css'

const Header = styled.h1`
  color: red;
`

const IndexPage = () => (
  <Layout>
    <Header>Atwood の法則</Header>
  // className に 先ほど読み込んだものに. でアクセスする
    // このコンポーネント内で CSS 名前空間が区切られるので良い
    <p className={testStyles.test}>
      JavaScript で書けるアプリケーションは全て、最終的に JavaScript
      で書かれることになっている。
    </p>
    <p>
      Any application that can be written in JavaScript, will eventually be
      written in JavaScript.
    </p>
    <ul>
      <li>
        <Link to="/about/">About me</Link>
      </li>
      <li>
        <Link to="/page-3/">Go to page 3</Link>
      </li>
    </ul>
  </Layout>
)

export default IndexPage

icon を変える

gatsby-config.js に書いてある icon のパスを変える
さしあたって元の画像と同じ512*512 の png にしたらうまくいった
キャッシュに残っている場合があるので、クリアする

layout コンポーネント

単なる react コンポーネントだが、内部に配置したコンテンツが children として入ってくるので、それを再配置する。

layout.js
// children を受け取るのがポイント
// <layout>中身</layout> として使った時に、中身がここに入ってくる
const Layout2 = ({ children, title, description, headerTitle }) => (
  <div>
    <Helmet
      title={title}
      meta={[{ name: 'description', content: description }]}
    >
      <html lang="en" />
    </Helmet>
    <Header siteTitle={headerTitle} />
    <div
      style={{
        margin: '0 auto',
        maxWidth: 960,
        padding: '0px 1.0875rem 1.45rem',
        paddingTop: 0,
      }}
    >
      {children} // ここで中身を配置
    </div>
  </div>
)

ファイルからデータを取得する

npm install --save gatsby-source-filesystem
gatsby-config.js
plugins: [
    { // このオブジェクトを追加する
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `src`,
        path: `${__dirname}/src/`,
      },
    },
    `gatsby-plugin-emotion`,
    {
      resolve: `gatsby-plugin-typography`,
      options: {
        pathToConfigModule: `src/utils/typography`,
      },
    },
  ],

npm start develop をサイド実行して例の GUI の画面で control + space で予測変換すると all files がでる。こんな感じで入れて、ファイル名とかが取れるのがわかる。

{
  allFile {
    edges {
      node {
        relativePath
        name
        size
      }
    }
  }
}

ファイル名をレンダリングしてみる

import React from 'react'
import { Link } from 'gatsby'
import { graphql } from 'gatsby'

import Layout from '../components/layout'

const GraphQlTest = ({ data }) => {
  console.log(data)
  console.log(data.allFile.edges.map(({ node }, index) => node.relativePath))
  return (
    <Layout>
      <h1>About Me</h1>
      {data.allFile.edges.map(({ node }, index) => {
        return <div key={node.relativePath}>{node.relativePath}</div>
      })}
      <Link to="/">Go back to the homepage</Link>
    </Layout>
  )
}

export const query = graphql`
  query {
    allFile {
      edges {
        node {
          relativePath
          prettySize
          extension
          birthTime(fromNow: true)
        }
      }
    }
  }
`

export default GraphQlTest

マークダウンを HTML にする

npm install --save gatsby-transformer-remark

単に gatsby-transformer-remark をプラグインの設定ファイルに追加する

プログロマティックに記事を作成する

async/await で以下のように公式サンプルは書き換えることができる。

exports.createPages = async ({ graphql, actions }) => {
  const result = await graphql(`
    {
      allMarkdownRemark {
        edges {
          node {
            fields {
              slug
            }
          }
        }
      }
    }
  `)
  console.log(result)
  console.log(JSON.stringify(result, null, 4))
}
9
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
7