The Node CLI supports a “require” flag, which allows you to preload a module when running Node.

node -r module/script index.js
node --require module/script index.js

When might you want to use this?

One example is the dotenv module, which extracts variables from a .env file in the root of your project, and adds them to the process.env object.

Due to the way import statements are resolved, it can be tricky to ensure that dotenv loads the environment variables before your application code.

The “require” flag solves this problem:

node -r dotenv/config index.js

It also works with ts-node:

ts-node -r dotenv/config index.ts