Reading environment variables from pug
Asked Answered
L

1

2

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?

Logbook answered 14/6, 2017 at 15:32 Comment(0)
S
4

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.

Semitic answered 14/6, 2017 at 16:15 Comment(2)
It's not an extra file, you were already passing options.json. Just put those variables into the same file and you have one file to worry about that has both the dynamic (process.env) stuff as well as the static options.Semitic
Haa, beautiful! Thanks. This way the js file outputs a json file, that's so simple. Thank you : ) Creativity at it's best.Logbook

© 2022 - 2024 — McMap. All rights reserved.