Home > Mobile >  Defining a loop within a script inside package.json
Defining a loop within a script inside package.json

Time:12-16

Is it possible to include a for loop inside a package.json file to recurse into subdirectories and execute a command in each:

# .env File
DIRECTORIES="Dir1, Dir2"
# package.json file in parent directory
"scripts": {
  "install-all-inefficient": "(cd ./dir/Dir1/ && npm install) && (cd ./dir/Dir2/ && npm install)",
  "install-all-ideal": ". .env && functionToLoopThroughDirectoriesDefinedInEnvironmentVariables",
},

I was looking at this: Defining an array as an environment variable in node.js as an example for defining the array, and then trying to somehow use process.env.DIRECTORIES to create a loop without writing too much ugly bash script.

CodePudding user response:

No, it is not possible to include a for loop inside a 'package.json' file. package.json is a JSON (JavaScript Object Notation) file, which is a text-based data format that is designed for use in JavaScript applications. JSON files do not support the use of loops or other programming constructs, so it is not possible to include a for loop in a 'package.json' file.

If you want to execute a command in each subdirectory of your project, you can use the 'npm run' command in combination with the 'find' command. For example, you could use the following command to execute a script called 'my-script' in each subdirectory of your project:

find . -type d -exec npm run my-script -- {} \;

This command will recursively search the current directory for all subdirectories and then execute the my-script script in each one.

The exact syntax and options for the find command may vary depending on your operating system and version of npm. You may need to consult the find and npm documentation for more information.

CodePudding user response:

You can try :

"install-all-ideal": ". .env; for dir in \"${DIRECTORIES[@]}\"; do (cd \"$dir\" && npm install); done"

with .env :

DIRECTORIES=("Dir1" "Dir2")
  • Related