Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to set a dotenv variable from package.json script?

I am using dotenv in my project to get variables from a .env file. I would like to be able to set a value in the .env(dotenv) file from package.json when running npm test. Something similar to this:

"scripts": {
    "test": "set ENV=test mocha './test/**/*.spec.js'",
    "start": "node app"
  }

my .env file is simply this:

ENV = development

I'm using windows. Thanks in advance for any help!

like image 808
N.K Avatar asked Sep 16 '25 14:09

N.K


1 Answers

You can use

"test": "ENV=test mocha './test/**/*.spec.js'"

in your npm script on Linux, and use

"test": "set ENV=test&&mocha './test/**/*.spec.js'"

on Windows.

BTW, if you need to cross platform, use cross-env so that your code can run on both Windows and Linux.

You can also use require.

For example, you have a ./test/test.env.js

// test/test.env.js
process.env.ENV = 'test';

and use require in your npm script like this:

"test": "mocha --require 'test/test.env.js' './test/**/*.spec.js'"
like image 184
NoobTW Avatar answered Sep 19 '25 06:09

NoobTW