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

Viewed 6066

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!

2 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'"

Yes you can do that, you can pass environment variables through commands too.

i.e. with your scripts:-

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

Just by using, I don't know how to help about the test script, I don't understand that, but I believe it must be something like this

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