C.2 LiveReload

As we briefly mentioned in Section 1.2, you can use blogdown::serve_site() to preview a website, and the web page will be automatically rebuilt and reloaded in your web browser when the source file is modified and saved. This is called “LiveReload”.

We have provided two approaches to LiveReload. The default approach is through servr::httw(), which will continuously watch the website directory for file changes, and rebuild the site when changes are detected. This approach has a few drawbacks:

  1. It is relatively slow because the website is fully regenerated every time. This may not be a real problem for Hugo, because Hugo is often fast enough: it takes about a millisecond to generate one page, so a website with a thousand pages may only take about one second to be fully regenerated.

  2. The daemonized server (see Section 1.4) may not work.

If you are not concerned about the above issues, we recommend that you use the default approach, otherwise you can set the global option options(blogdown.generator.server = TRUE) to use an alternative approach to LiveReload, which is based on the native support for LiveReload from the static site generator. At the moment, this has only been tested against Hugo-based websites. It does not work with Jekyll and we were not successful with Hexo, either.

This alternative approach requires two additional R packages to be installed: processx and later. You may use this approach when you primarily work on plain Markdown posts instead of R Markdown posts, because it can be much faster to preview Markdown posts using the web server of Hugo. The web server can be stopped by blogdown::stop_server(), and it will always be stopped when the R session is ended, so you can restart your R session if stop_server() fails to stop the server for some reason.

The web server is established via the command hugo server (see its documentation for details). You can pass command-line arguments via the global option blogdown.hugo.server. The default value for this option is c('-D', '-F'), which means to render draft and future posts in the preview. We want to highlight a special argument --navigateToChanged in a recent version of Hugo, which asks Hugo to automatically navigate to the changed page. For example, you can set the options:

options(blogdown.hugo.server = c("-D", "-F", "--navigateToChanged"))

Then when you edit a source file under content/, Hugo will automatically show you the corresponding output page in the web browser.

Note that Hugo renders and serves the website from memory by default, so no files will be generated to public/. If you need to publish the public/ folder manually, you will have to manually build the website via blogdown::hugo_build() or blogdown::build_site().