0

This is my package.json:

"scripts": {
 "start": "bash do_something.sh && jest",
 "...": "..."
}

In my package, there is the package.json and do_something.sh files at the package root, and a test_file.spec.ts module in ./src.

So doing npm run start from the CLI first runs the shell script with bash, then when the shell script finishes, it runs jest. This works fine so far.

However, there is a hardcoded constant, say FOO, inside do_something.sh (as FOO="bar") and inside the test module (as const FOO = "bar";). Instead of having to change the constant in both files upon each run, I would like to be able to set it from the CLI when calling the script, by doing something like:

npm run start --FOO=bar

I would then want to intercept that CLI argument from within the npm script definition in the package.json, and set it as an environment variable accessible within the do_something.sh shell script, and within the test_file.spec.ts module.

So in the package.json I would do something like:

"scripts": {
 "start": "env FOO=$npm_config_FOO bash do_something.sh && jest",
 "...": "..."
}

(I am using the npm_config_ approach from here)

Then from within do_something.sh:

echo $FOO

And within test_file.spec.ts:

console.log(process.env.FOO);

I think I am close to getting it working, just a few missing steps I think.

asked May 22, 2020 at 15:11

1 Answer 1

1

I think it's very close to what you have

"scripts": {
 "start": "export FOO=\"$npm_config_FOO\"; bash do_something.sh && jest"
 ...
}

which is going to export FOO and it will be available in bash and jest environments.

answered May 22, 2020 at 23:14
Sign up to request clarification or add additional context in comments.

1 Comment

This looks good, although it has the downside of not being platform independent.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.