How to Reference Environment Variables From. Env File with Cross-Env?

I have to set node environment variables using cross-env in package.json but the values are in a .env file.

I've tried the following formats but none has worked.

cross-env API_KEY=%API_KEY% && ...
cross-env API_KEY=$API_KEY && ...
cross-env %API_KEY% && ...
1

1 Answer

cross-env is used to set environment variables inline when running node commands.

cross-env NODE_ENV=production webpack --config build/webpack.config.js

However when populating environment variables from .env files you'll need to use dotenv or similar.

It's common to have a separate .env file for each environment (.env.development, .env.production...). To configure this with dotenv you need to run dotenv.config at the root of your project, to pick the right .env file.

dotenv.config({
    path: path.resolve(__dirname, `${process.env.NODE_ENV}.env`)
});
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest