Automating hugo development with npm scripts
I wanted one command I could run that would automatically watch my SCSS files and HTML files, and build them upon change, and serve up the resulting website. In order to avoid complicating development by introducing a task runner as an additional dependency (such as grunt or gulp) I decided to try using npm scripts. It turned out to be very simple and easy!
First, I install npm (OS is Arch Linux):
Then, from the root of my hugo project I use npm init
to create my package.json
. It asks a series of questions which are quite straightforward to follow:
After this you will have a bare-bones package.json
such as the one shown above. Note that we did not specify a test command, but npm created a stub for the test command anyway in the "scripts"
section. We can run this with npm test
:
As expected, the command fails with Error: no test specified
. It is easy to add your own custom commands. As a simple example, if you want running npm serve
to run hugo serve --buildDrafts
, then add the following script to your package.json
:
npm scripts can call system commands, other npm packages, and even call other npm scripts. This ability to chain npm scripts can be very useful for building up basic commands into useful compound commands.
For example, first make a sass:build
command which builds your SCSS files into CSS. Then make a sass:watch
command which uses npm onchange
to watch your SCSS files and call sass:build
if they are modified. Finally, create a start
command which calls sass:build
before using parallelshell
to simultaneously run sass:watch
and serve
:
The above allows you to simply call npm start
, and then you can edit your SASS files or hugo HTML/Markdown files (etc) and they are automatically rebuilt and the browser reloads the page.
All notes in this series:
- (1) Automating hugo development with npm scripts
- (2) normalize-scss with hugo
- (3) Automatic image thumbnails in Hugo from static directory
- (4) Escaping Hugo shortcodes within Hugo markdown
- (5) Hugo tag and category pages
- (6) Bind hugo to localhost for development
- (7) Hugo 0.37 does not support h6 markdown heading
- (8) Install Hugo testing distribution on Debian
- (9) Hugo anchors next to headers
- (10) Hugo: Migrating from Pygments to Chroma
- (11) Hugo: Global resources