Andre Pena
Andre Pena

Reputation: 59336

How to set environment variables in a cross-platform way?

For Windows, my Node scripts should look like this:

"scripts": {
    "start-docs": "SET NODE_ENV=development&&babel-node ./docs/Server.js"
}

But on Linux there's no SET, so it would be like this:

"scripts": {
    "start-docs": "NODE_ENV=development&&babel-node ./docs/Server.js"
}

Is there a way to declare environment variables in a way that is consistent and cross-platform?

Upvotes: 22

Views: 11248

Answers (3)

Stan Mots
Stan Mots

Reputation: 1218

If you don't wanna use any third-party tools there is an easy way to achieve this using a nodejs script.

Step-by-step guide:

  1. Create ./scripts/set-env.js file with the following content:

import { argv, env } from "node:process"
import { spawn } from "node:child_process"

// Set your custom env variables here
const extenv = {
    NODE_ENV: "development",
}

spawn(argv[2], argv.slice(3), {
    env: { ...env, ...extenv },
    stdio: "inherit",
})

Notes:

  • argv[2] is a passed-in command to run in a child shell
  • argv.slice(3) - passed-in arguments
  • ...env - used to preserve current shell environment variables
  • stdio: "inherit" - used to pipe the child shell output into the current shell
  1. Edit your package.json's scripts section:

"scripts": {
    "set-env": "node ./scripts/set-env.js",
    "start-docs": "npm run set-env -- babel-node ./docs/Server.js"
}

Notes: -- is used to pass command and arguments to the set-env script.

Advantages

  • Cross-platform
  • No third-party dependencies
  • Fully customisable

Upvotes: 1

Andre Pena
Andre Pena

Reputation: 59336

I recently came across the cross-env project. It's pretty straight-forward

{
  "scripts": {
    "build": "cross-env NODE_ENV=production webpack --config build/webpack.config.js"
  }
}

That will set the build environment variable to production regardless of the OS.

Upvotes: 29

DanielKhan
DanielKhan

Reputation: 1208

I would vote against setting this in package.json because environment variables should be set dependent on your environment while package.json is most likely the same for every environment (you commit it to your version control system, right?). Instead you should use something like dotenv if you are looking for a clean and generic solution.

Upvotes: 3

Related Questions