Gatsby.js 是一個基於 React 的靜態網站生成器node
Blazing fast static site generator for React
前一陣看 React 官網文檔的時偶然發現的react
Kyle Mathews 小哥在 2015 年開了這個坑git
到目前已有 17k+ 的 star,以及被 React、Reason、Sourcegraph 等用來生成官方文檔,還獲得了業界大佬的好評github
We use it for https://reactjs.org/ . Nice to be able to use React component abstraction for layout etc, load initial page as HTML but then have fast navigation thanks to code splitting. Unlike Jekyll I don’t constantly think about static/dynamic separation. @Dan Abramov
下面來一個快到爆炸的新手教程?npm
node version >= 8.0.0dom
安裝 gatsby cli編輯器
npm install --g gatsby-cli
初始化網站
gatsby new tutorial-part-one https://github.com/gatsbyjs/gatsby-starter-hello-world
https://github.com/gatsbyjs/gatsby-starter-hello-world
被稱爲 Starter,除此以外還有不少具備各類功能的 Starterui
Run 起來this
cd tutorial-part-one && gatsby develop
用你最心愛的編輯器/IDE,給 src/pages/index.js
加點料
import React from "react"; export default () => <div style={{ color: `tomato` }}> <h1>Hello Gatsby!</h1> <p>What a world.</p> <img src="https://source.unsplash.com/random/400x200" alt="" /> </div>
似裏 React,仍是熟悉的味道
Gatsby 提供了組件 gatsby-link
來,用你最心愛的編輯器/IDE 給 src/pages/index.js
加個連接 /page-2/
import React from "react"; import Link from "gatsby-link"; export default () => <div style={{ color: `tomato` }}> <h1>Hello Gatsby!</h1> <p>What a world.</p> <img src="https://source.unsplash.com/random/400x200" alt="" /> <br /> <div> <Link to="/page-2/">Link</Link> </div> </div>
而後增長文件 src/pages/page-2.js
import React from "react"; import Link from "gatsby-link"; export default () => ( <div> <p>Hello world from my second Gatsby page</p> <Link to="/">back home</Link> </div> );
接下來,再你最心愛的編輯器/IDE 給 src/pages/index.js
加個連接 /counter/
import React from "react"; import Link from "gatsby-link"; export default () => <div style={{ color: `tomato` }}> <h1>Hello Gatsby!</h1> <p>What a world.</p> <img src="https://source.unsplash.com/random/400x200" alt="" /> <br /> <div> <Link to="/page-2/">Link</Link> </div> <div> <Link to="/counter/">Counter</Link> </div> </div>
細心的朋友必定能從 counter 這個名字猜到些什麼,此次增長的是一個帶有交互能力的頁面,functional component
是不夠的,要使用 經過 class component
中的 state
來提供交互能力
import React from "react"; class Counter extends React.Component { constructor() { super() this.state = { count: 0 } } render() { return ( <div> <h1>Counter</h1> <p>current count: {this.state.count}</p> <button onClick={() => this.setState({ count: this.state.count + 1 })}>plus </button> <button onClick={() => this.setState({ count: this.state.count - 1 })}>minus </button> </div> ) } } export default Counter
接下來咱們把剛纔寫的東西部署到 GitHub Pages
npm install gh-pages --save-dev
最後用你最心愛的編輯器/IDE,修改 gatsby-config.js
(/project-name
即爲 https://github.com/username/project-name
中的末尾)
module.exports = { pathPrefix: `/project-name`, }
gatsby build --prefix-paths && gh-pages -d public
執行完畢後,打開 https://username.github.io/project-name/