node: require option to preload modules

2020-08-13

 | 

~1 min read

 | 

185 words

In learning about different approaches to loading environment variables in Node projects, I came across an option for Node that can require dependencies from the command line.

For example, one common way to load environment variables within a Node project is to use dotenv like so:

Define your variables within a .env file:

.env
MY_VAR=TEST

Load the environment variables with dontenv’s config method as quickly as possible, e.g., in the entry point to the app:

index.js
require(dotenv).config()

console.log(process.env.MY_VAR)

Assuming dotenv is installed when we run this project:

node index.js

We’ll print to the console:

SUCCESS

But this is only because “as early as possible” in our application, we called the config method.

It turns out we can preload this configuration (using the -r --require CLI option for Node) and eliminate the line:

index.js
- require(dotenv).config()

console.log(process.env.MY_VAR)
node --require dotenv/config index.js

And we will still see our environment variables are loaded successfully:

SUCCESS

Pretty nifty! Particularly if you don’t want dotenv to be a production dependency where environment variables are managed by some external service.



Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!