Running a root-level npm script in a workspace context
Asked Answered
H

1

7

I have a script defined in the root-level package.json:

{
  "workspaces": [
    "packages/*"
  ],
  "scripts": {
    "clean": "rm -rf lib dist"
  },
  "private": true
}

I would like to run this script in the context of the the packages/example package, which does not define a clean script. (I want to reuse this script across all of my workspaces

I tried running npm -w packages/example run clean and npm run clean -w packages/example but these commands search for a clean script inside packages/example/package.json:

npm ERR! Error: Missing script: "clean"

To be clear, I want to delete the lib and dist folders from packages/example by running a script at the workspace root.

Note: I'm using this clean script as an example. The real scripts are more complicated and I don't want to duplicate them across all of the workspaces

Haematic answered 18/3, 2023 at 15:23 Comment(0)
G
0

The only workaround I found with this is to call it with --include-workspace-root option, which includes the workspace root context. The problem is that it will also try to run the script in the current package context, so if you have clean script defined in your example package it will also run. If it doesn’t have a script though it will raise an error, thankfully it could be suppressed by --if-present flag.

npm run --include-workspace-root --if-present clean
Grainger answered 8/2 at 2:54 Comment(1)
That works for the most part, but the script is still being run from the workspace root context, so paths are relative to the workspace root. I want them to be relative to each individual package rootHaematic

© 2022 - 2024 — McMap. All rights reserved.