DEV Community

Cover image for npm workspaces: npm run and exec
Ruy Adorno
Ruy Adorno

Posted on

npm workspaces: npm run and exec

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:

Latest comments (4)

Collapse
 
robertal99 profile image
robertal99

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.

Collapse
 
spic profile image
Sascha Picard

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

Collapse
 
klvenky profile image
Venkatesh KL

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.

Collapse
 
spic profile image
Sascha Picard

Thanks for elaborating!