The business line has been very busy these days, and it has just calmed down, so there is little time for in-depth research on some new things. If you want to think about it, you can use a Web framework Gatsby. Recently, you can check Dan’s personal blog, which is also built with Gatsby. Github.com/gaearon/ove…
Basic introduction
In recent years, Gatsby has been quite popular, especially in foreign countries, with a star count of 44.5K. Thanks to its many excellent features in generating static websites, it has gained great popularity.
Advantages as a Web framework:
- There is almost perfect support for Markdown files
- The speed is very fast, reflected in the loading/refreshing aspects, using almost all the optimization means of static station
- Theme many
- Plenty of room for manoeuvre
- Good SEO support
We chose it because we wanted to build a blog of our own, while Gatsby as a framework has high flexibility: it can be very simple, with MD analysis and a theme. It is based on react/graphQL/webpack and other familiar technology stacks and development modes. It can also add TS support /SSR support, which can be used for continuous practice
The final goal to achieve: after the completion of development, you only need to put your new MD documents into the corresponding folder and submit to Github to update the blog site!
Initial Environment Configuration
Step 1, the next global CLI
npm install -g gatsby-cli
You can use this command to see if the global package installed by NPM exists in Gatsby – CLI
npm list --depth=0 -global
Take a look at the available command gatsby –help
Pull the project directly with the official configuration
Gatsby new [project] https://github.com/gatsbyjs/gatsby-starter-hello-world
CD [Project Name]
gatsby develop
At this point, the project is pulled down and a static site is started
In this case, you can open http://localhost:8000 in the browser window to view the interface
Also open http://localhost:8000/___graphql an enhanced version of graphiQL (to help you check the type of graphQL) as shown below ⤵️
Directory Structure description
| - / public / / packaging of epigenetic output static website file | - / content / / can also be other name, General in the place of the file such as the MD | - / SRC | - / pages / / page file (the file will be here as a routing) | - / templates / / template file | - / static | - / types/store/ts | - type definition Gatsby - config. Js / / is the most important documents, which need to do a lot of configuration | -- gatsby - node. Js / / | -- gatsby - SSR. A special file, js / / SSR can not establish | - gatsby - the js / / Browser API related calls, can not be createdCopy the code
In the Pages folder, there is a routing convention. All files are parsed into routes according to the relative path and file name when packaged by the framework. Another way to create routes is to use the API createPages in the Gatsby – Node file, which will be discussed later
Ts support (skip this paragraph)
To add TS support, type yarn add typescript gatsby-plugin-ts and configure tsconfig.json in the root directory as follows: ⤵️
This way, every query you make in graphiQl will generate its TS type intelligently
Adding an MD document
Next we can add the MD document
I’m in the habit of creating a new blog folder in the Content folder and putting all MD documents in the following format
-- path: "/blog/firstblog" date: "2020-07-02" title: "firstblog" tags: [" trivia "] -- my firstblog my firstblog...Copy the code
In general, I will write the above attributes, especially path, which will be manually used as a real route later (if you don’t like to manually declare the path, you can also add node mapping path).
PS: Writing MD documents must be standardized, each line in the code block should be preceded by 4 indentation
The plug-in configuration
Plugins are configured in plugins in the gatsby-config.js file in the top-level directory
Install the Gatsby -source-filesystem // to retrieve the Md and YML/YMAL files in the project. Note that the path should be configured to contain the location of the Md file
// Parse the extracted MD class files into json and other data sources
The above two are required plug-ins for MD processing ⤴️
(Optional, as far as possible) Install the Gatsby plugin-catch-links // so that the browser does not refresh the entire page while navigating the local page, just like SPA
(Optional, try to install) Installation of Gatsby -remark-images // Processing MD and other referenced images, may need support of Gatsby – plugin-Sharp
See ⤵️ for the gatsby-config.js file
module.exports = {
plugins: [{resolve: `gatsby-plugin-ts`.options: {
tsLoader: {
logLevel: 'warn',},forkTsCheckerPlugin: {
eslint: true,},fileName: `types/graphql-types.ts`.codegen: true.codegenDelay: 250,}},'gatsby-plugin-catch-links',
{
resolve: `gatsby-source-filesystem`.options: {
path: `${__dirname}/content/blog`.// This address must refer to the address of the MD file in order to be recognized by the GraphQL service
name: `blog`,}}, {resolve: `gatsby-source-filesystem`.options: {
path: `${__dirname}/content/assets`.name: `assets`,}},'gatsby-plugin-sharp'.// A library for deep compression and image cutting (no need to set gatsby-remark-images)
{
resolve: 'gatsby-transformer-remark'.options: {
plugins: [{resolve: `gatsby-remark-images`.options: {
maxWidth: 590.linkImagesToOriginal: false,}},`gatsby-remark-prismjs`.// This will be covered later]}},],}Copy the code
Parsing an MD file
Add a template file for MD: We’ll create a new blog. TSX file in the templates folder under SRC
export interface ITemplate {
data: { markdownRemark: MarkdownRemark};
}
import React from "react";
import { graphql } from "gatsby";
import "./blog.css";
import { MarkdownRemark } from ".. /.. /types/graphql-types";
export default function Template({
data, // this prop will be injected by the GraphQL query below.
}: ITemplate) {
const { markdownRemark } = data // data.markdownRemark holds your post data
const { frontmatter, html } = markdownRemark
return (
<div className="blog-post-container" style={{ margin: `3rem auto`, maxWidth: 650.padding: `0 1rem`}} >
<div className="blog-post" >
<h1>{frontmatter && frontmatter.title}</h1>
<h2>{frontmatter && frontmatter.date}</h2>
<div
className="blog-post-content"
dangerouslySetInnerHTML={{ __html: html| | "}} / ">
</div>
</div>)}Copy the code
Also use createPages plus page parsing in the Gatsby – Node file
exports.createPages = async ({ actions, graphql, reporter }) => {
const { createPage } = actions;
const blogPostTemplate = require.resolve(`./src/templates/blog.tsx`);
const result = await graphql(` { allMarkdownRemark { edges { node { frontmatter { path } } } } } `)
// Handle errors
if (result.errors) {
reporter.panicOnBuild(`Error while running GraphQL query.`)
return
}
result.data.allMarkdownRemark.edges.forEach(({ node }) = > {
createPage({
path: node.frontmatter.path, // This is the path property of the three-line wrap in the MD document
component: blogPostTemplate,
context: {
// additional data can be passed via context}})})}Copy the code
Add page-level requests
The template file above has been configured quite well, but there is still one thing missing, his data source!
At the beginning of http://localhost:8000/___graphql we can select pageQuery at the page level, as shown in the sample code, the blog. TSX template file is page level, and we can then export a Query as the data source.
In addition to exporting the page-level component by default, the same template file (blog.tsx) also exports a constant query, set to the template with the graphQL tag and queried between two back quotes:
MarkdownRemark is a query for the field of a single MD file, passing in the path variable and using eq: $path to determine which file it is
export const query = graphql` query($path: String!) { markdownRemark(frontmatter: { path: { eq: $path } }) { html frontmatter { date(formatString: "MMMM DD, YYYY") path title } } } `
Copy the code
PS: The constant could have been called a different name than Query, because Gatsby would have graphQL look for exported GraphQL strings from files, not specific variables, but note that there can only be one query per file.
MD code block highlighted
Code block highlight we can configure PrismJS
www.gatsbyjs.org/packages/ga… The above is more detailed. In a nutshell, configure gatsby-remark-prismjs under the gatsby- Transformer -remark plug-in, and finally introduce CSS under the gatsby- Browser.js file
require("prismjs/themes/prism-solarizedlight.css")
PS: Prism itself provides a variety of code highlighting themes that can be implemented in different CSS
Md other style custom words we can write a CSS file to configure, we look at its properties in the node classname corresponding to write CSS, do not elaborate
List page
At this point, there are MD files displayed in each path. You can write some custom CSS for the classname of each node to make it look better. What is missing is the home page
We usually set up the front page as a list of blogs, with titles and abstracts for each blog
Create a new index.tsx file in the Pages folder
interface IBlogIndexProps {
data: { allMarkdownRemark: MarkdownRemarkConnection};
// location: Location;
}
import React from "react"
import { graphql, Link } from "gatsby"
import { MarkdownRemark, MarkdownRemarkConnection } from ".. /.. /types/graphql-types"
const BlogIndex: React.FC<IBlogIndexProps> = ({ data }) = > {
return (
<div>
<h1> Let's Do Some Amazing Things </h1>
<h4>{data.allMarkdownRemark.totalCount} Posts</h4>
{data.allMarkdownRemark.edges.map(({ node }: { node: MarkdownRemark}) => (
<div key={node.id}>
<h3 style={{marginBottom: 5}} >
<Link to={node.frontmatter && node.frontmatter.path| | '} >{node.frontmatter && node.frontmatter.title}{" "}</Link>
<span style={{color: "#bbb}} ">- {node. The frontmatter && node. The frontmatter. Date}</span>
</h3>
<p>{node.excerpt}</p>
</div>
))}
</div>)}export const query = graphql` query { allMarkdownRemark(sort: { order: DESC, fields: [frontmatter___date] }) { totalCount edges { node { id frontmatter { title date(formatString: "DD MMMM, YYYY") path } excerpt } } } } `
export default BlogIndex
Copy the code
Subject to use
Theme can be used in two ways, one is directly pull github other people’s theme as a project (in fact, is directly white whoring other people’s template), the other is introduced as a plug-in, can configure it to take effect directory scope, such as a website has several modules, a route under the theme affected, the same can configure multiple themes.
(The theme module originally wrote a lot, think or delete, all in their own exploration)
The deployment of online
The Gatsby cloud can directly connect to its Own Github to make a sustainable CICD
www.gatsbyjs.com/dashboard/s…
The website can identify its own private library by logging in with its own Github. The next fool-trick is to designate its own Gatsby repository and build it automatically.
Yarn. lock file (do not submit yarn.lock file for the project you are playing around with. Some packages loaded on the Intranet were recorded by yarn.lock, but the address was not found during deployment.)
Once set up, preview will have a fixed online address, which will be updated automatically a few minutes later when you submit the code on Github
This is the online address of the project gatsbymGuy.gtsb.io /
extension
So far, a simple blog site has become, later to write a blog directly into the MD file folder submitted to Github.
But There are many more features and advanced apis worth knowing about gatsby. Here are a few
The high-level createResolvers and onCreateNode apis in the Gatsby -node.js file can be seen here
The Mapping node types(Mapping nodes) in the gatsby-config.js file are also interesting, so you can try to understand them
The onCreateWebpackConfig API in the Gatsby -node.js file can schedule the WebPack packing process
There are a lot of tedious site construction work, such as adding 404 pages, SEO, global layout and so on are also relatively simple, here is not a spread out
The follow-up plan
There are some interesting features planned for initial expansion, such as various queries, online editing and adding, and open comments
During this period of time, I took some spare time to explore this framework, which is quite interesting
Some information
The official website of Gatsby is www.gatsbyjs.org/
Assigned to www.gatsbyjs.cn/
Recommend a theme github.com/maxpou/gats…
If there are any shortcomings, please point them out in the comments section