5.2 Hexo

The ideas of using Hexo (https://hexo.io) are very similar to what we have applied to Jekyll in the previous section. I have also prepared a minimal example in the GitHub repository yihui/blogdown-hexo.

The key components of this repository are still .Rprofile, R/build.R, and R/build_one.R. We set the option blogdown.generator to hexo, the build.method to custom, and the default subdirectory for new posts to source/_posts.

options(
  blogdown.generator = 'hexo',
  blogdown.method = 'custom',
  blogdown.subdir = 'source/_posts'
)

The script R/build.R is similar to the one in the blogdown-jekyll repository. The main differences are:

  1. We find all Rmd files under the source/ directory instead of the root directory, because Hexo’s convention is to put all source files under source/.

  2. We call system2('hexo', 'generate') to build the website.

For the script R/build_one.R, the major difference with the script in the blogdown-jekyll repository is that we set the base.dir option for knitr, so that all R figures are generated to the source/ directory. This is because Hexo copies everything under source/ to public/, whereas Jekyll copies everything under the root directory to _site/.

local({
  # fall back on '/' if baseurl is not specified
  baseurl = blogdown:::get_config2('root', '/')
  knitr::opts_knit$set(
    base.url = baseurl, base.dir = normalizePath('source')
  )

  # input/output filenames as two arguments to Rscript
  a = commandArgs(TRUE)
  d = gsub('^source/_?|[.][a-zA-Z]+$', '', a[1])
  knitr::opts_chunk$set(
    fig.path   = sprintf('figure/%s/', d),
    cache.path = sprintf('cache/%s/', d)
  )
  knitr::knit(
    a[1], a[2], quiet = TRUE, encoding = 'UTF-8', envir = .GlobalEnv
  )
})

This repository is also automatically built and deployed through Netlify when I push changes to it. Since Hexo is a Node package, and Netlify supports Node, you can easily install Hexo on Netlify. For example, this example repository uses the command npm install && hexo generate to build the website; npm install will install the Node packages specified in packages.json (a file under the root directory of the repository), and hexo generate is the command to build the website from source/ to public/.