npm environment variables


You can access npm environment variables from package.json vars:

npm run env | grep npm_package_

But to load them in your Node.js module, you’ll need dotenv and dotenv-expand.

dotenv

Make sure you have a package.json. If you don’t have one, create one:

npm init --yes

Install both dotenv and dotenv-expand:

npm install dotenv dotenv-expand

Create a .env file with your expanded environment variables:

# .env
NAME=$npm_package_name
VERSION=${npm_package_version}

Load the environment variables in your module index.js:

// index.js
const dotenv = require('dotenv');
const dotenvExpand = require('dotenv-expand');

dotenvExpand(dotenv.config());

console.log(process.env.NAME, process.env.VERSION);

If you run the command:

node index.js

You won’t see anything logged to the console.

That’s because npm environment variables are only available via npm.

So create an npm script in your package.json:

{
  "scripts": {
    "start": "node index.js"
  }
}

Then when you run the script:

npm start

You will see the package name and version logged to the console.

Gist

See example gist below:



Please support this site and join our Discord!