Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load .env environment variables when running npm task

Let's say we have a .env file with some variables specified:

AWS_PROFILE=hsz
ENVIRONMENT=development

There is also a simple npm task defined:

{
  "name": "project",
  "version": "0.0.1",
  "scripts": {
    "deploy": "sls deploy"
  }
}

But runnning npm run deploy ignores our .env definition.

It can be resolved with better-npm-run like:

{
  "name": "project",
  "version": "0.0.2",
  "scripts": {
    "deploy": "bnr deploy"
  },
  "betterScripts": {
    "deploy": "sls deploy"
  },
  "devDependencies": {
    "better-npm-run": "^0.1.1",
  }
}

but this looks like an overhead - especially when we have 10+ tasks.

Is there a better way to always load .env without proxying all tasks via better-npm-run?

like image 723
hsz Avatar asked Jan 02 '23 15:01

hsz


1 Answers

A bit ugly, but you could try something like this:

"scripts": {
  "deploy": "export $(cat .env | xargs) && sls deploy"
}

This will export all environment variables from the .env file before running sls deploy.

There are some variations to this tehnique in this answer.

Not very clean but it avoids usage of an extra module.

like image 157
mihai Avatar answered Jan 05 '23 15:01

mihai