npm workspaces: npm run and exec
Ruy Adorno

Ruy Adorno @ruyadorno

About: Immigrant to beautiful Canada 🇨🇦 working on Node.js things @Google, previously npm cli team @GitHub • Node.js core collaborator • JavaScript • CLI • Open Source • DX [he/him]

Location:
Montreal, Canada
Joined:
Apr 9, 2018

npm workspaces: npm run and exec

Publish Date: Mar 24 '21
27 4

I bring good news!

Workspaces support for both npm run and npm exec landed today in npm@7.7.0, it adds the new -w and -ws config options that allows for running scripts in workspaces from the top-level folder, e.g:

assuming a file structure:

.
├── package.json ->  { "workspaces": ["packages/*"] }
└── packages
    ├── a
    │   ├── index.js
    │   └── package.json
    ├── b
    │   ├── index.js
    │   └── package.json
    └── c
        ├── index.js
        └── package.json
Enter fullscreen mode Exit fullscreen mode

It's now possible to run a script in a given workspace. In order to run one of the scripts available in the workspace named a, at location: ./packages/a/ you may run from the root of your project, either of the following:

  • npm run <script-name> -w a
  • npm run <script-name> -w ./packages/a

It also supports the test|start|stop|restart top level comands, so if you're using any of these you can just add -w <workspaces-name> and it should work as expected, e.g:

  • npm test -w a (will run the tests of workspace a)

In case you want to run a script against all the configured workspaces, there's a workspaces configuration option that enables just that:

  • npm test -ws

Lastly it's also possible to run scripts in a group of workspaces by using the path to their parent folder as the workspace config value. That means running npm test -w ./packages will run tests in all workspaces nested at the ./packages location.

Want to learn more about it?

We updated the docs, see:

You may also want to check out the changelog:

Comments 4 total

  • Sascha Picard
    Sascha Picard Mar 25, 2021

    What would be a use case to use multiple package.json files with own scripts within a repo?

    • Venkatesh KL
      Venkatesh KLMar 27, 2021

      For projects which have a bunch of small & isolated utilities which can be used together as a single project or be used as a standalone module.
      Ex:lodash.
      You can install a small part of lodash alone using
      npm install loadash/uniq
      Instead of installing entire lodash library.

  • robertal99
    robertal99Jul 7, 2021

    Hello, without touching the subject of npm workspaces, could you give me a brief explanation of 'npm exec', I was reading in the documentation and I did not understand you and on the internet I do not find much explanatory material about this command, I would appreciate it.

Add comment