npmnpm-scripts

npm scripts: read .env file


I have a simple requirement: In my npm scripts package.json file I have the line:

{
    "scripts": {
        "example": "some-lib --argument --domain \"https://tld.com\""
    }
}

Now I want the "domain" to be factored out.

First try is to use $npm_package_config, which works:

{
    "config": {
        "domain": "https://tld.com"
    },
    "scripts": {
        "example": "some-lib --argument --domain \"$npm_package_config_domain\""
    }
}

But I want the domain loaded from an local .env file.

I did not find any solution out there to read the contents of an env file inside npm scripts on the command line.

Can somebody give me a hint to a possible solution for this problem?


Solution

  • A much easier solution is to just use bash to parse the env file in-line and extract the variable you want:

    Assuming your .env file looks like:

    DOMAIN=https://tld.com
    
    "scripts": {
      "example": "some-lib --argument --domain $(grep DOMAIN .env | cut -d '=' -f2)"
    }