简体   繁体   中英

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!

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM