Costa Costa -4 years ago 233
Node.js Question

Reading environment variables from pug

I'm using pug to compile static html. My own static site generator, kinda.

I have no node.js server code besides this line in my package.json file:

"watch-pages": "pug -O options.json -w pages/ --out _static-website/"


But, I need to read environment variables like NODE_ENV inside of pug templates. How might I do this?

Answer Source

This is fairly simple; you may find another way to do it but what I tried (successfully) was to simply define a .js file to pass as the options parameter which includes the variables I wanted. For example:

// env.js
module.exports = { env: process.env };

Then the template can be something like:

// tmp.pug
ul
  each e in env
    li=e

And you can then run pug -O env.js tmp.html and it will create a env.html with the environment variables rendered as list items.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download