1.3 Preview book

As you work, you may start a local server to live preview this HTML book. This preview will update as you edit the book when you save individual .Rmd files. You can start the server in a work session by using the RStudio add-in “Preview book”, or from the R console:

bookdown::serve_book(dir = ".", output_dir = "_book", preview = TRUE, quiet = FALSE)

You pass the root directory of the book to the dir argument, and this function will start a local web server so you can view the book output using the server. The default URL to access the book output is http://127.0.0.1:4321.

Depending on your IDE, the url will be opened in either internal or external web browser.

The server will listen to changes in the book root directory: whenever you modify any files in the book directory, serve_book() can detect the changes, recompile the Rmd files, and refresh the web browser automatically.

  • If you set preview = FALSE, the function will recompile the book, which can take a longer time.

  • quiet = TRUE will suppress output (e.g., the knitting progress) in the console.

    Even if the compiling messages are distracting, they tell you the status of the book rendering, so you may want to keep the default anyway.

To stop the server, run servr::daemon_stop(1) or restart your R session.

bookdown::serve_book() is better than using live preview in VS Code because the html viewer does not blink continuously when you edit and save the .Rmd files. Besides, live preview do not refresh contents automatically.

💡 Tip: 

  • Use serve_book() while working on your book to see live changes, then run render_book() once you are ready to publish.

  • serve_book() and preview_chapter are slow as they recompile the entire book when you save any file.

    Suggested action: rmarkdown::render_site("onefile.Rmd") to render the current active file. Go to docs/ and right-click onefile.html > select Show Preview to open in browser. ✅

    The web preview will not update automatically (no flashing), so you need to re-render the file when you make changes.


Bibliography

# automatically create a bib database for R packages
knitr::write_bib(c(
  .packages(), 'bookdown', 'knitr', 'rmarkdown'
), 'packages.bib')