Search code examples
node.jsnpmjestjsdotenv

how to change the path in dotenv with various script commands (in package.json) such as : start , test , etc


well my problem is when I want to switch my script command in package.json like from "start" to "test" for running my Jest test which its commands like :

"scripts": {
  "start": "nodemon express/***",
  "serve": "node express/***",
  "dev": "node express/***",
  "test": "jest --watch"
},

and I call dotenv in my project like this

require("dotenv").config({
path: "express/config/.env",
});
  

The code above, help my to using my environment file like .env but the problem is that when I want to test my project and I want to switch my script command (in package.json) from like "start" to "test" and change the main path of dotenv environment to something like test.env


Solution

  • You could pass the environment type as an environment variable into your program like so. Note: you will need to use cross-env if you require multi-platform support.

    Unix version:

    "scripts": {
      "start": "NODE_ENV=production nodemon express/***",
      "serve": "NODE_ENV=production node express/***",
      "dev": "NODE_ENV=dev node express/***",
      "test": "NODE_ENV=test jest --watch"
    }
    

    cross-env version:

    "scripts": {
      "start": "cross-env NODE_ENV=production nodemon express/***",
      "serve": "cross-env NODE_ENV=production node express/***",
      "dev": "cross-env NODE_ENV=dev node express/***",
      "test": "cross-env NODE_ENV=test jest --watch"
    }
    

    And then access them using the normal method of process.env.NODE_ENV

    const envVariablePaths = {
      "production": "/path/here",
      "dev": "path/here",
      "test": "path/here",
    }
    require("dotenv").config({
      path: envVariablePaths[process.env.NODE_ENV],
    })
    

    More documentation can be found here