欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

开始使用盖茨比 - 构建项目

最编程 2024-03-21 11:16:00
...

开始

  • 安装 Gatsby 脚手架
npm install -g gatsby-cli
  • 新建项目

gatsby new [projectName][starter]:根据 starter 创建一个新项目

gatsby new gatsby-blog-demo https://github.com/gatsbyjs/gatsby-starter-hello-world

我们这里使用官方最简单版本的 hello-world 模板进行开发,如果你直接使用

gatsby new gatsby-blog-demo

默认会使用 gatsby-starter-default 来新建项目

  • 运行项目
cd gatsby-blog-demo
gatsby develop

打开 localhost:8000,就可以看到输出了一句Hello world!

常用命令

这里介绍 Gatsby 的几个常用命令:

  • gastby develop:开启热加载开发环境
  • gastby build:打包到 public 下,构建生产环境用的优化过的静态网站所需的一切静态资源、静态页面与 js 代码
  • gatsby serve:在打包之后,启动一个本地的服务,供你测试刚才"gatsby build"生成的静态网页

GraphiQL

打开http://localhost:8000/__graphql,就会看到 GraphQL 的调试界面,这里可以查看所有的数据、以及调试 query 语句是否返回相应的数据。可以直接在左侧点击选中,就可以自动生成 query 语句。

可能出现的警告

如果运行后你的控制台出现:

React-Hot-Loader: react-hot-dom patch is not detected. React 16.6+ features may not work.

可以这样解决:

npm install @hot-loader/react-dom

在根目录下新建gatsby-node.js

exports.onCreateWebpackConfig = ({ getConfig, stage }) => {
  const config = getConfig()
  if (stage.startsWith('develop') && config.resolve) {
    config.resolve.alias = {
      ...config.resolve.alias,
      'react-dom': '@hot-loader/react-dom'
    }
  }
}

再重新启动项目,就可以消除这个警告

项目结构

├── .cache
├── public
├── src
|  └── pages            // 该文件夹下的文件会被映射为路由
|     └── index.js
├── static              // 静态资源
├── .prettierignore
├── .prettierrc
├── gatsby-config.js    // 基本配置文件
├── LICENSE
├── package.json
├── README.md
└── yarn.lock

推荐阅读