0

I'd like inside my package.json execute some script which will set environment variables that my app could use. I need something like this (in my package.json)

  "scripts": {
    "dev": "set-env-vars.sh && webpack-dev-server --hot --inline & cd server && NODE_ENV=development node app.js",
  },

This is my set-env-vars.sh file:

#!/bin/bash
export ENV_MONGODB_URI="mongodb://localhost:27017/mydb"
...

I know that I need use source or . to export my variables into shell, this is working in shell, but not for my package.json dev-script.

Any solutions to achieve that? Thank you.

1 Answer 1

1

The problem is in single ampersand (&) after webpack-dev-server invocation. Trailing ampersand directs the shell to run the command in the background. In practice, your command will be split into 2 parts, which are going to be invoked in separate shells asynchronously. If you use ampersand (&) intentionally, then you should source env vars in both parts like this:

. ./set-env-vars.sh && webpack-dev-server --hot --inline & . ./set-env-vars.sh && cd server && NODE_ENV=development node app.js

so, variables from set-env-vars.sh will be available for both webpack-dev-server and node

Or if you want to run it synchronously:

. ./set-env-vars.sh && webpack-dev-server --hot --inline && cd server && NODE_ENV=development node app.js
Sign up to request clarification or add additional context in comments.

3 Comments

The problem is that when I add . or source inside script, I have receive this: sh: line 0: .: set-env-vars.sh: file not found
I think you should use ./set-env-vars.sh instead of set-env-vars.sh to execute file from current directory.
So finally this is works: webpack-dev-server --hot --inline & . ./set-env-vars.sh && cd server && NODE_ENV=development node app.js Thank you! )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.