如何使用Gatsby建立博客 / How to build a blog with Gatsby

Nowadays we all gotta get on board and use React and GraphQL, like this friend of mine in his company.

The idea of a flexible and customizable alternative to REST does sound like something brilliant if you ask me.

But I always have a problem with the "new technologies" around the Front End (if any of us is still using this term). I am not saying I do not like them. c'mon, I came from jQuery, why would I not like the dazzling frameworks like React or Vue? It is just that there are so much innovation in this field and I find it hard to keep up with the steps of others since I do not work on these stuff myself that often, and last time I checked, Bootsrap and Angular are trending. A 5 min read is not enough to understand how React works, and that is my whole point. A couple years apart, you are going to have to remold your eyes to see the front end world even if you are only trying to build an up to date blog.

Anyways, React and GraphQL look kind of cool so I took the time to read a bit by giving up kayaking in Lake Tahoe. It did make me feel I'm behind the steering wheel when learning to use Gatsby.

Gatsby

  1. Install Gatsby
npm install gatsby-cli --save
  1. Use a "starter" to start your Gatsby project unless you want to write even the package.json yourself.

For example, if you use the default starter -- gatsby-starter-default, you get a directory structure like this:

├── node_modules
├── src
├── .gitignore
├── .prettierrc
├── gatsby-browser.js
├── gatsby-config.js
├── gatsby-node.js
├── gatsby-ssr.js
├── LICENSE
├── package-lock.json
├── package.json
├── README.md
└── yarn.lock

There are a few things we should pay attention to here:

  • gatsby-browser.js: where you implement Gatsby browser APIs. Use it sometimes for debugging and analytics, etc.
  • gatsby-config.js is the major configuration file where you configure all the constants (your site metadata like author, site url, etc.) as well as the plugins you use
  • gatsby-node.js
  • gatsby-ssr.js: implementing Gatsby Server Rendering APIs. It can be useful as it gives you more freedom to modify your site during server rendering. Like onPreRenderHTML allows you to check/change head/body/post-body components, etc.
  • package.json: people with Node.js programming experiences will know about this file, which essentially defines your gatsby site as a node project -- mainly configures the dependencies. The package-lock.json above is just a verbose version of this.
  • yarn.lock: if you use yarn as the package manager instead of npm, you need to care about this file. Ignore it otherwise.

Besides the default, there are a whole lot of other starters you can choose from. Most of which goes under MIT license so we are good using them if all we what is a configurable and good-looking blog site.

  1. Build it.
gatsby develop

builds and hosts the site locally. Ideal for testing as it dynamically loads your changes without stopping the server and rebuild.

gatsby build

does a full production build. You get properly generated static HTMLs and JS bundles. You can test this production package by

gatsby serve

Markdown

Back in the days when we built blogs using Jekyll or Hexo we have the practice of producing posts from the markdown files in a separate directory. Gatsby keeps the tradition.

In order to transform markdown to HTML, we will need to use the help of GraphQL and this Transformer plugin.

Let us add this plugin to your project by injecting it into your package.json:

npm install --save gatsby-transformer-remark

Check your gatsby-config.js file, be sure you add this plugin:

module.exports = {
  siteMetadata: {
    title: `Pandas Eating Lots`,
  },
  plugins: [
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `src`,
        path: `${__dirname}/src/`,
      },
    },
    `gatsby-transformer-remark`,
    `gatsby-plugin-emotion`,
    {
      resolve: `gatsby-plugin-typography`,
      options: {
        pathToConfigModule: `src/utils/typography`,
      },
    },
  ],
}

Then GraphQL is granted with the data of allMarkdownRemark from which you can access your markdown files. Like:

export const pageQuery = graphql`
  query IndexQuery {
    allMarkdownRemark(
        limit: 1000,
        filter: { frontmatter: { layout: { eq: "post" }, draft: { ne: true } } },
        sort: { order: DESC, fields: [frontmatter___date] }
      ){
      edges {
        node {
          fields {
            slug
            categorySlug
          }
          frontmatter {
            title
            date
          }
        }
      }
    }
  }
`;

Code highlighting

Now that we have the transformer plugin, we then use PrismJs to enable code highlighting:

  {
      resolve: 'gatsby-transformer-remark',
      options: {
        plugins: [
          {
            resolve: 'gatsby-remark-prismjs',
            options: {
              classPrefix: "language-",
              inlineCodeMarker: null,
              aliases: {},
              showLineNumbers: false,
            }
          },
        ]
      }
    }

There are different ways to mark up the code but in markdown files, the easiest way would be using something like this:

  ```python

Instead of just ``` in front of your code snippet.

There is a good note where you can read more about this.

A word on hosting -- Netlify

Well, I know there has been some debates going on over which hosting service works better or smoother than the other ones and stuff like that. You might think about Firebase, Heroku, and even Github Pages. Netlify is used here because they have good marketing. Well, the truth is, I chose it cuz it has got the catchiest name among them all and I do not have any interest in wasting my time on understanding how these services are different from each other. Seriously.

It is unbelievably easy to deploy a Gatsby project on Netlify. You hit this, that and that, and you are done.

No, I am serious. If you get on Netlify, you hit this:

New site

that:


that

(authorize its access to Github) and that:

that

and you are done.

Like it or not, it just works this way.

The thing is, we might or might not want to configure our deploy context. Basically you will want to configure a netlify.toml file which kind of looks like this:

[Settings]
ID = "Your_Site_ID"

# Settings in the [build] context are global and are applied to all contexts unless otherwise overridden by more specific contexts.  

[build]
  # This is the directory to change to before starting a build.
  base  = "project/"
  # NOTE: This is where we will look for package.json/.nvmrc/etc, not root.
  # This is the directory that you are publishing from (relative to root of your repo)
  publish = "project/build-output/"
  # This will be your default build command
  command = "echo 'default context'"
  # This is where we will look for your lambda functions
  functions = "project/functions/"

# Production context: All deploys from the Production branch set in your site's deploy settings will inherit these settings.
[context.production]
  publish = "output/"
  command = "make publish"
  environment = { ACCESS_TOKEN = "super secret", NODE_ENV = "8.0.1" }

In which you get to play with a lot of configs like build and output directories, commands for deployment, redirects and even headers.

Also, sometimes you would want to specify the node version you are using especially if you are trying to be weird and use some old version just because you like that number, and you should configure this info on the Netlify backend:


Env Vars

or through a .nvmrc file: #set-node-ruby-or-python-version

One thing that makes Netlify think highly of itself is that it uses HTTPS. But from time to time, you will see the Mixed Content issue coming up. Meaning, HTTP contents are being referenced or showing up in your site and both HTTP and HTTPS are being used when loading the same page. There is an article here to help clarify the idea and Mozilla helped categorize the issues.

Like what you do with Github Pages and most other hosting services, whenever you push your new posts to your Github repositoy for this Gatsby project, the blog deployed gets automatically updated. Along with the other stuff I mentioned above, basically you have minimum transitional cognitive cost when switching from other blog generators as well as hosting services.


I looked up through the smoke of my cigarette and my eye lodged for a moment upon the burning coals, and that old fancy of the crimson flag flapping from the castle tower came into my mind, and I thought of the cavalcade of red knights riding up the side of the black rock. Rather to my relief the sight of the mark interrupted the fancy, for it is an old fancy, an automatic fancy, made as a child perhaps. The mark was a small round mark, black upon the white wall, about six or seven inches above the mantelpiece.

--"The Mark on the Wall" by Virginia Woolf (1882-1941)

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,744评论 6 502
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,505评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,105评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,242评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,269评论 6 389
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,215评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,096评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,939评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,354评论 1 311
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,573评论 2 333
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,745评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,448评论 5 344
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,048评论 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,683评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,838评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,776评论 2 369
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,652评论 2 354

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,322评论 0 10
  • 今天是我第一次来到这里,想说的话太多,但却又不知道从何说起。 最近发生的事实在是太多了去,妈妈走啦,她说再也...
    YF一一一一阅读 118评论 0 0
  • 今晨的风有点凉 吹过四十年的沧桑 柳树叶落了又长 雨季来了又走 老树的年轮一圈圈地 讲着那循环的老故事 云从一处飘...
    寒山1978阅读 128评论 0 1
  • 为啥程序人员总和产品人员吵架,或许是天生的吧。 或许程序人员是理性的,产品人员是感性的。 但是作为把生活提取出来成...
    陆小飞阅读 900评论 2 1
  • 宝贝背诗的速度越来越快了,每天都知道自己写什么作业,也知道了自己的作息时间了!
    为幸福锁阅读 162评论 0 0