Cross-Platform Environment Setup with cross-env
You'll learn how to set environment variables consistently across Windows, macOS, and Linux using the cross-env package.
The Cross-Platform Problem
You've learned that setting environment variables differs between shells: export NODE_ENV=production works on Unix-based systems (macOS/Linux), but Windows CMD requires set NODE_ENV=production. This means your npm scripts won't work the same way everywhere, forcing teammates on different operating systems to maintain separate scripts.
What is cross-env?
cross-env is an npm package that provides a single, unified syntax for setting environment variables that works identically across all platforms. It acts like a translator, converting your command into whatever format the current operating system needs.
Think of it like a universal power adapter: you plug in the same way regardless of which country (OS) you're visiting, and it handles the conversion automatically.
How It Works
First, install cross-env:
npm install --save-dev cross-env
Then use it in your package.json scripts:
{
"scripts": {
"start": "cross-env NODE_ENV=production node app.js",
"dev": "cross-env NODE_ENV=development DEBUG=true node app.js"
}
}
Now npm start works identically on Windows, macOS, and Linux. The cross-env command sets the environment variables before running your Node script, and your code accesses them normally with process.env.NODE_ENV.
You can set multiple variables in one command by simply listing them with spaces between each KEY=value pair.
Key Takeaway: Use cross-env in npm scripts to set environment variables consistently across all operating systems, eliminating platform-specific script variations and making your project truly portable.