10

I have a npm project which I'm using many flags when calling node.js, so my package.json scripts are a little confusing, like this:

"scripts": {
        "test": "node --use_strict -r dotenv/config --experimental-vm-modules node_modules/.bin/jest",
        "testwatch": "node --use_strict -r dotenv/config --experimental-vm-modules node_modules/.bin/jest -watchAll",
        "start": "node --use_strict -r dotenv/config --experimental-vm-modules ./src/index"
    },

Is there a way to specify the node.js flags in a single parameter in the package.json file so that it is passed to all scripts simultaneously? Or if you can give me another suggestion to make these commands more organized it would be useful too. Thanks.

1 Answer 1

13
+50

I can only think of two solutions for this problem.

  1. Using package.json config variable
  2. Using an alias

Solution 1:

You can access config variables in the scripts by $npm_package_config_<variable-name>

package.json file

"config": {
    "testflags": "--use_strict -r dotenv/config --experimental-vm-modules"
},
"scripts": {
    "test": "node $npm_package_config_testflags node_modules/.bin/jest"
}

Solution 2:

By the way I don't know How to do this on windows machine!!! So I'm assuming you're using Mac or GNU/Linux OS.

Create an alias in your shellrc file (e.g., ~/.bashrc for bash and ~/.zshrc for zsh etc.).

Add the following in your ~/.bashrc or ~/.zshrc file or whatever shellrc file you have.

alias node_test='node --use_strict -r dotenv/config --experimental-vm-modules'

Note: Here you've to provide the full path of the dotev/config file. To get full path of the config.js file go to the dotenv directory and run readlink -f config. Copy the full path of file and replace dotenv/config in the above alias.

Then save the file and source it by running source ~/.bashrc in the terminal.

Now in your package.json file:

"scripts": {
    "test": "node_test node_modules/.bin/jest"
}
Sign up to request clarification or add additional context in comments.

1 Comment

Was something exactly like solution 1 that I was looking for. Thanks.

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.