3

I have a monorepo with several workspaces within it. It has been very common for me to use chained npm scripts for simple tasks instead of using a task runner. So for example, the following configuration (pseudo code) is very common for me and usefull as well, specially for pre and post build scripts

"scripts": {   
    "prebuild:task1":"task1 --task1-arguments",  
    "prebuild:task2":"task2 --task2-arguments",  
    "prebuild": "npm run prebuild:task1 && npm run prebuild:task2",   
    "build":"build-script --build-arguments",  
}

So the above is the package.json for the child worskpace itself and then in the master package.json I have the call to the script that triggers the build for that workspace.

build:packageA: "npm run build -w packageA"

All seems working well but the chained "npm run script" inside the workspace is actually execute in the context of the master monorepo and not inside that particular workspace.

So, in summary, the first call is to run the build script in the workscape and then triggers the prebuild script of that workspace BUT as that script execute chained npm run scripts those are run in the context of the master repo which happens that they don't exist in there. So the callstack might be ...

(master) build:packageA
(packageA) prebuild
(master) npm run prebuild:task1 >>>> EXIT ERROR

The only way I found, up to now, to bypass this issue was to make my child workspace a monorepo itself holding zero woskpaces. Essentially I have a "workspaces" key in its package.json pointing to the root directory. This enables me to use the -w flag in the scripts section so to refer all scripts to itself. So my current workaround looks like this ...

"workspaces": ["."],  
"scripts": {  
   "prebuild:task1":"task1 --task1-arguments",  
   "prebuild:task2":"task2 --task2-arguments",  
   "prebuild": "npm run prebuild:task1 -w packageA && npm run prebuild:task2 -w packageA",   
   "build":"build-script --build-arguments -w packageA"  
}

Isn't there already a better way to solve this? Thanks in advance to everyone!

denik1981
  • 370
  • 2
  • 12

1 Answers1

0

Following this post https://stackoverflow.com/a/67060676 I found out that npm changed the way it calls nested scripts in workspaces.

I ran into similar issues like you while running npm@7.5, but the feature was introduced in npm@7.7. Updating node to v17 and npm to 8.3 resulted in everything is running as intended.

In my case I wanted to execute nested npm run build commands in workspaces.

StephanB
  • 315
  • 2
  • 17