Levelling up Monorepos with npm Workspaces

Rate this content
Bookmark

Learn more about how to leverage the default features of npm workspaces to help you manage your monorepo project while also checking out some of the new npm cli features.

This talk has been presented at JSNation 2022, check out the latest edition of this JavaScript Conference.

FAQ

NPM Workspaces is a set of features in NPM that helps manage multiple nested packages within a single top-level package. It centralizes the installation of all dependencies into a single Node Modules folder and creates a single package lock file, making it ideal for managing monorepos.

To create a new workspace in an NPM project, use the 'npm init' command in your project directory. This ensures that every necessary step is taken, such as creating a folder with a package.json file inside it and adding the folder name to the workspaces field of your top-level package.json.

The 'npm ls' command is used in NPM Workspaces to list each workspace and its dependencies. This command is workspace-aware and highlights the specific workspaces in your project, helping you manage and visualize dependencies more effectively.

To add a dependency to a specific workspace, use the 'npm workspace' command followed by the workspace name and the package you wish to install. For example, 'npm workspace [workspace_name] add [package_name]' will add the specified package to the targeted workspace.

You can manage and run scripts across different workspaces by using the npm run command along with workspace configuration. For example, specifying 'npm run [script_name] --workspace=[workspace_name]' executes the script within the context of the specified workspace.

The recommended way to set up a new workspace in an NPM project is by using the npm init command. This command ensures that all necessary steps are followed, including creating a new folder with a package.json file and adding the workspace to the workspaces field in your top-level package.json.

The 'no hoist' feature allows specific dependencies to be installed directly within a workspace's own node_modules directory rather than being hoisted to the top-level node_modules folder. This can be essential for certain packages that rely on their location in the file system to function properly.

Ruy Adorno
Ruy Adorno
25 min
20 Jun, 2022

Comments

Sign in or register to post your comment.
Video Summary and Transcription
This Talk provides an introduction to NPM Workspaces and covers various aspects of using them, including starting a workspace with npm init, adding dependencies, forcing correct library versions, running scripts and orchestrating in a monorepo, and using npm pkg and npm exec. The examples provided demonstrate real-life use cases and highlight the flexibility and control that NPM Workspaces offer. The speaker also mentions improvements and future developments in the NPM CLI, emphasizing the importance of correct declarations in the package.json file and the ability to manage data across all workspaces.

1. Introduction to NPM Workspaces

Short description:

Hello, and welcome to Leveling Up Monorepos with NPM Workspaces. Let me start by introducing myself. My name is Rui Adorno. I'm a software developer in the NPM CLI team of GitHub. I have been working on the NPM CLI for almost three years now. I work on the NPM v7 rewrite and a lot of those features that we're going to be talking about here today, and especially workspaces.

Hello, and welcome to Leveling Up Monorepos with NPM Workspaces. Let me start by introducing myself. My name is Rui Adorno. I'm a software developer in the NPM CLI team of GitHub. I have been working on the NPM CLI for almost three years now. I work on the NPM v7 rewrite and a lot of those features that we're going to be talking about here today, and especially workspaces. So, I'm super excited to be sharing some of that work with you here today.

And let's start with an overview what we're going to be covering here today. Let's start with an intro to what is NPM Workspaces and then cover some very practical examples with trying to get as close to real-life usage as possible and also note some of the stuff that you should be looking forward to. So, let's get started.

NPM Workspaces. What is it? So, let's start with Workspaces, which is basically this concept introduced by Yarn a while ago, and basically it is a way to help you manage many packages within a single repo. And for NPM, NPM Workspaces is kind of the broad name we gave the set of features that help you achieve that. Basically help you manage multiple nested packages within a single top level package. So, it's going to help you centralize the installation of all the dependencies into a single Node Modules folder, so you're going to end up also having only a single package log file. And there are some advantages to that. It is definitely the ideal way for managing Monorepos, and thanks to that, you can have a single place to manage all your issues and basically manage your project and your community. So, but also into the technical side, you can also centralize, have a single place to run all your tests, peer, linting, anything that you can kind of imagine. You kind of need everything together to get your project running with all the packages. You can have it all in a single place. So it might help a lot depending on the style of the project you're trying to achieve. So another thing I would like to note here is timeline just to give a little bit of this notion of how we've been iteratively improving on NPM workspaces. And you can see it all started in August, 2020 with the release of the release 7.0 of the NPM CLI that first introduced support to installing NPM the workspaces. And then in version 7.7, another big one which kinda first introduced the configuration properties of a workspace or targeting all the workspaces and the first command that support them with NPM run and NPM exec. So there weren't many more, but I just kinda wanted to illustrate how we've been improving and you can definitely keep waiting, you can definitely wait to see more improvements coming on NPM workspaces.

So let's get started with some examples here. I have this project that I have on the left-hand side here that is a sample app that I've put together trying to get as close as possible for real-life project. This is kind of like a web app that consists in two different services. So you can see, I have my user sync service, my web app service, and I even configure a third workspace here, which is the slides that you're seeing right now. So they're all part of this monorepo app that I'm managing here.

2. Using npm init to Start a Workspace

Short description:

And with that, I hope to put some examples that are real close to how you would use this in your real life. So you can see they all have a bunch of dependencies here using Next.js, the services using Fastify. Moving forward, I'd like to highlight npm init. It's probably the best way of just starting your workspace because it's going to make sure every step that is needed is going to end up being there.

And with that, I hope to put some examples that are real close to how you would use this in your real life. So you can see they all have a bunch of dependencies here using Next.js, the services using Fastify. So I can just quickly start by running NPM ls here and we can see how, and ls is a command that is aware of workspaces and it's going to highlight each of the workspaces in my project and even list the dependencies of each workspace when I run an NPM ls. So it's the first command to know that has first class support to workspaces.

So moving forward here, I'd like to highlight npm init. It's probably the best way of just starting your workspace because it's going to make sure every step that is needed is going to end up being there. So basically everything you need to track a nested package as a workspace is make sure you have the folder with a package JSON inside it, inside your project, and then just add the folder name to your workspaces field of your package JSON in the top level. So using npm init is going to make sure that those requirements are there. So I'm gonna run a quick example here in my sample app, I'm gonna create a new workspace. Let's say I'm gonna call it the website. So I can run npm init, I'm using dash Y here to just accept all the defaults and I'm targeting a website. So that's going to create a website folder with a package.json file inside it, and it's going to print the contents of the package.json file over here. And as I mentioned before, the other really important point that npm init takes care of is placing the reference to the website inside my package.json file in my top level folder. So with that, it is all set up. If I npm install here, now the install tree is going to be tracking the website. And if I run npm ls again, I'm going to see website listed as one of the workspaces here highlighted in green. So that is definitely the recommended way to get started with a new workspace inside your project.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Levelling up Monorepos with npm Workspaces
DevOps.js Conf 2022DevOps.js Conf 2022
33 min
Levelling up Monorepos with npm Workspaces
Top Content
NPM workspaces help manage multiple nested packages within a single top-level package, improving since the release of NPM CLI 7.0. You can easily add dependencies to workspaces and handle duplications. Running scripts and orchestration in a monorepo is made easier with NPM workspaces. The npm pkg command is useful for setting and retrieving keys and values from package.json files. NPM workspaces offer benefits compared to Lerna and future plans include better workspace linking and adding missing features.
End the Pain: Rethinking CI for Large Monorepos
DevOps.js Conf 2024DevOps.js Conf 2024
25 min
End the Pain: Rethinking CI for Large Monorepos
Today's Talk discusses rethinking CI in monorepos, with a focus on leveraging the implicit graph of project dependencies to optimize build times and manage complexity. The use of NX Replay and NX Agents is highlighted as a way to enhance CI efficiency by caching previous computations and distributing tasks across multiple machines. Fine-grained distribution and flakiness detection are discussed as methods to improve distribution efficiency and ensure a clean setup. Enabling distribution with NX Agents simplifies the setup process, and NX Cloud offers dynamic scaling and cost reduction. Overall, the Talk explores strategies to improve the scalability and efficiency of CI pipelines in monorepos.
Federated Microfrontends at Scale
React Summit 2023React Summit 2023
31 min
Federated Microfrontends at Scale
Top Content
Watch video: Federated Microfrontends at Scale
This Talk discusses the transition from a PHP monolith to a federated micro-frontend setup at Personio. They implemented orchestration and federation using Next.js as a module host and router. The use of federated modules and the integration library allowed for a single runtime while building and deploying independently. The Talk also highlights the importance of early adopters and the challenges of building an internal open source system.
Scale Your React App without Micro-frontends
React Summit 2022React Summit 2022
21 min
Scale Your React App without Micro-frontends
This Talk discusses scaling a React app without micro-frontend and the challenges of a growing codebase. Annex is introduced as a tool for smart rebuilds and computation caching. The importance of libraries in organizing code and promoting clean architecture is emphasized. The use of caching, NxCloud, and incremental build for optimization is explored. Updating dependencies and utilizing profiling tools are suggested for further performance improvements. Splitting the app into libraries and the benefits of a build system like NX are highlighted.
The Age of Monorepos
JSNation 2022JSNation 2022
25 min
The Age of Monorepos
Today's Talk is about the world of monorepos, their history, benefits, and features. Monorepos address challenges in web development, such as slow build processes and unstable connections on mobile devices. Collocation in monorepos enables easy sharing of functions and components among projects. Speed and efficiency in monorepos are achieved through collocation, dependency graphs, and task orchestration. Monorepo tools like Learnr offer features such as caching and distributed task execution. Monorepos provide code sharing, consistent tooling, and automated migration, resulting in a 10x developer experience.
Remixing Your Stack in a Monorepo Workspace
Remix Conf Europe 2022Remix Conf Europe 2022
22 min
Remixing Your Stack in a Monorepo Workspace
Let's talk about remixing our stack in a Monorepo workspace, which allows for incremental migration and is suitable for transitioning from a Next.js app to a remix stack. Refactoring may be required for feature-specific and Next.js-coupled components, but the process is simplified because the features have already been moved out. Configuring the Monorepo to reference packages locally and linking them to the Next.js application is necessary. Nx provides benefits like fast refreshing, pre-configured setups, and features like local and remote caching.

Workshops on related topic

React at Scale with Nx
React Summit 2023React Summit 2023
145 min
React at Scale with Nx
Top Content
Featured WorkshopFree
Isaac Mann
Isaac Mann
We're going to be using Nx and some its plugins to accelerate the development of this app.
Some of the things you'll learn:- Generating a pristine Nx workspace- Generating frontend React apps and backend APIs inside your workspace, with pre-configured proxies- Creating shared libs for re-using code- Generating new routed components with all the routes pre-configured by Nx and ready to go- How to organize code in a monorepo- Easily move libs around your folder structure- Creating Storybook stories and e2e Cypress tests for your components
Table of contents: - Lab 1 - Generate an empty workspace- Lab 2 - Generate a React app- Lab 3 - Executors- Lab 3.1 - Migrations- Lab 4 - Generate a component lib- Lab 5 - Generate a utility lib- Lab 6 - Generate a route lib- Lab 7 - Add an Express API- Lab 8 - Displaying a full game in the routed game-detail component- Lab 9 - Generate a type lib that the API and frontend can share- Lab 10 - Generate Storybook stories for the shared ui component- Lab 11 - E2E test the shared component
Node Monorepos with Nx
Node Congress 2023Node Congress 2023
160 min
Node Monorepos with Nx
Top Content
WorkshopFree
Isaac Mann
Isaac Mann
Multiple apis and multiple teams all in the same repository can cause a lot of headaches, but Nx has you covered. Learn to share code, maintain configuration files and coordinate changes in a monorepo that can scale as large as your organisation does. Nx allows you to bring structure to a repository with hundreds of contributors and eliminates the CI slowdowns that typically occur as the codebase grows.
Table of contents:- Lab 1 - Generate an empty workspace- Lab 2 - Generate a node api- Lab 3 - Executors- Lab 4 - Migrations- Lab 5 - Generate an auth library- Lab 6 - Generate a database library- Lab 7 - Add a node cli- Lab 8 - Module boundaries- Lab 9 - Plugins and Generators - Intro- Lab 10 - Plugins and Generators - Modifying files- Lab 11 - Setting up CI- Lab 12 - Distributed caching
Finding, Hacking and fixing your NodeJS Vulnerabilities with Snyk
JSNation 2022JSNation 2022
99 min
Finding, Hacking and fixing your NodeJS Vulnerabilities with Snyk
WorkshopFree
Matthew Salmon
Matthew Salmon
npm and security, how much do you know about your dependencies?Hack-along, live hacking of a vulnerable Node app https://github.com/snyk-labs/nodejs-goof, Vulnerabilities from both Open source and written code. Encouraged to download the application and hack along with us.Fixing the issues and an introduction to Snyk with a demo.Open questions.
Build Web3 apps with React
React Summit 2022React Summit 2022
51 min
Build Web3 apps with React
WorkshopFree
Shain Dholakiya
Shain Dholakiya
The workshop is designed to help Web2 developers start building for Web3 using the Hyperverse. The Hyperverse is an open marketplace of community-built, audited, easy to discover smart modules. Our goal - to make it easy for React developers to build Web3 apps without writing a single line of smart contract code. Think “npm for smart contracts.”
Learn more about the Hyperverse here.
We will go over all the blockchain/crypto basics you need to know to start building on the Hyperverse, so you do not need to have any previous knowledge about the Web3 space. You just need to have React experience.