Try   HackMD

Gatsby 常用功能簡介

參考連結: https://www.gatsbyjs.com/docs/

Page 的構成

Layout, Component, CSS module, query
Gatsby 頁面常用 component 及 Styling 官方教學
Gatsby Link
Use the <Link> component

// src/pages/index.js import * as React from 'react' import { Link } from 'gatsby' const IndexPage = () => { return ( <main> <title>Home Page</title> <h1>Welcome to my Gatsby site!</h1> <Link to="/about">About</Link> <p>I'm making this by following the Gatsby Tutorial.</p> </main> ) } export default IndexPage

Styling

CSS module 官方教學

  • 每個 .js(component) 對應一個 module.scss(css) 放在同一個目錄底下
  • 從 scss import className 填入 tag 的 className

Query for Data with GraphQL

GraphQL 官方教學

npm run develop gatsby develop 網址:http://localhost:8000/___graphql

image alt

  • 根據需求將選取需要的資料,回傳的資料會是 json 的格式
  • gatsby-source-filesystem plugin: 可以用來存取本機端的資料(static 中的images 或是 markdowns)
  • page query: query頁面生成需要的資料,並傳入page component.
  • 觀察下面兩張圖可以發現結構完全對應
query MyQuery { site { siteMetadata { title } } }
{ "data": { "site": { "siteMetadata": { "title": "My First Gatsby Site" } } }, "extensions": {} }

範例格式

import * as React from 'react' import { Link, useStaticQuery, graphql } from 'gatsby' import { container, heading, navLinks, navLinkItem, navLinkText } from './layout.module.css' const Layout = ({ pageTitle, children }) => { const data = useStaticQuery(graphql` query { site { siteMetadata { title } } } `) return ( <div className={container}> <title>{pageTitle} | {data.site.siteMetadata.title}</title> <header>{data.site.siteMetadata.title}</header> </div> ) } export default Layout

Add Features with Plugins

新增 Plugin 的步驟

  1. Install the plugin using npm.
  2. Configure the plugin in your site’s gatsby-config.js file.
  3. Use the plugin features in your site, as needed.

範例:

用 npm 安裝該套件

npm install plugin-name

修改並設定 gatsby-config.js

// gatsby-config.js module.exports = { siteMetadata: { title: "My First Gatsby Site", }, plugins: [ { resolve: "plugin-name", options: { // Check the plugin README for what options go in here } }, ] }

常用套件

  1. "gatsby-plugin-image"
  2. "gatsby-plugin-sharp"

Create Pages Programmatically

Gatsby 生成頁面 官方教學

  • Use Gatsby’s Filesystem Route API to dynamically create new pages for your blog posts.
  • Add a query variable to a page query.