Gatsby 入門

示例倉庫https://github.com/XYShaoKang...css

初始化項目

初始化方式一:node

# 安裝全局命令行工具 gatsby,而後使用 gatsby 初始化項目
yarn global add gatsby-cli # or npm install -g gatsby-cli
gatsby new gatsby-hello-world https://github.com/gatsbyjs/gatsby-starter-hello-world

初始化方式二:react

# 若是不想全局安裝 gatsby,能夠使用 npx
npx gatsby new gatsby-hello-world https://github.com/gatsbyjs/gatsby-starter-hello-world

進入項目,運行程序,在瀏覽器打開http://localhost:8000/查看效果git

cd gatsby-hello-world
yarn develop

hello-world-init-preview.png

hello-world 比較簡單,沒有太多依賴,而官方的一些稍微複雜點的模板,通常都會帶一個插件 gatsby-plugin-sharp,很容易安裝失敗.若是安裝失敗,能夠看看這個 臨時解決方法

初始化以後目錄結構:github

├── .cache # 運行緩存目錄
├── node_modules # 保存安裝的模塊
├── public # 編譯後文件的保存目錄
├── src
│   └── pages # Gatsby 會將 pages 目錄下的組件將解析爲具備路徑的頁面
│       └── index.js
├── static
├── .gitignore
├── .prettierignore
├── .prettierrc
├── LICENSE
├── README.md
├── gatsby-config.js
├── package.json
└── yarn.lock

支持 styled-components

安裝依賴npm

yarn add gatsby-plugin-styled-components styled-components babel-plugin-styled-components

配置gatsby-config.jsjson

module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-styled-components`,
      options: {},
    },
  ],
}

使用styled-components,修改src/pages/index.jssegmentfault

import React from 'react'
import styled from 'styled-components'

const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: palevioletred;
`

const Wrapper = styled.section`
  padding: 4em;
  background: papayawhip;
`

export default () => (
  <Wrapper>
    <Title>Hello World!</Title>
  </Wrapper>
)

重啓服務,運行查看效果瀏覽器

hello-world-styled-components-preview.png

解析 Markdown 文件

  1. 安裝依賴
yarn add gatsby-source-filesystem gatsby-transformer-remark
  1. 配置gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-styled-components`,
      options: {},
    },
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `docs`,
        path: `${__dirname}/docs/`,
      },
    },
    {
      resolve: `gatsby-transformer-remark`,
      options: {},
    },
  ],
}
  1. 添加演示文檔用於測試,在項目根目錄新建文件夾docs,在docs下新建demo.md,粘貼如下內容
---
title: '演示文檔'
---

這是一篇簡單的演示文檔
  1. 修改src/pages/index.js用來渲染文檔
import React from 'react'
import styled from 'styled-components'

const Title = styled.h1`
  font-size: 1.5em;
  margin: 0;
  padding: 0.5em 0;
  color: palevioletred;
  background: papayawhip;
`

const Content = styled.div`
  margin-top: 0.5em;
`
export default ({ data }) => {
  const {
    frontmatter: { title },
    excerpt,
  } = data.allMarkdownRemark.edges[0].node
  return (
    <>
      <Title>{title}</Title>
      <Content>{excerpt}</Content>
    </>
  )
}

export const query = graphql`
  query {
    allMarkdownRemark {
      edges {
        node {
          frontmatter {
            title
          }
          excerpt
        }
      }
    }
  }
`

重啓服務,查看效果緩存

hello-world-parse-markdown-preview.png

相關資源

相關文章
相關標籤/搜索