示例仓库https://github.com/XYShaoKang...
初始化方式一:
# 安装全局命令行工具 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
初始化方式二:
# 如果不想全局安装 gatsby,可以使用 npx npx gatsby new gatsby-hello-world https://github.com/gatsbyjs/gatsby-starter-hello-world
进入项目,运行程序,在浏览器打开http://localhost:8000/查看效果
cd gatsby-hello-world yarn develop
hello-world 比较简单,没有太多依赖,而官方的一些稍微复杂点的模板,一般都会带一个插件gatsby-plugin-sharp
,很容易安装失败.如果安装失败,可以看看这个临时解决方法
初始化之后目录结构:
├── .cache # 运行缓存目录 ├── node_modules # 保存安装的模块 ├── public # 编译后文件的保存目录 ├── src │ └── pages # Gatsby 会将 pages 目录下的组件将解析为具有路径的页面 │ └── index.js ├── static ├── .gitignore ├── .prettierignore ├── .prettierrc ├── LICENSE ├── README.md ├── gatsby-config.js ├── package.json └── yarn.lock
安装依赖
yarn add gatsby-plugin-styled-components styled-components babel-plugin-styled-components
配置gatsby-config.js
module.exports = { plugins: [ { resolve: `gatsby-plugin-styled-components`, options: {}, }, ], }
使用styled-components
,修改src/pages/index.js
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> )
重启服务,运行查看效果
yarn add gatsby-source-filesystem gatsby-transformer-remark
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: {}, }, ], }
docs
,在docs
下新建demo.md
,粘贴以下内容--- title: '演示文档' --- 这是一篇简单的演示文档
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 } } } } `
重启服务,查看效果