Lerna is a tool which helps to manage the npm packages and versioning of monorepos projects. it has been widely used by many nodejs application such babel, reactjs, etc.
Monorepos is the concept of managing multiple projects in a single git repo. Applications such as Babel, React, Angular and ember etc were built using the monorepos method.
- Main Repo (Babel-core)
- Package 1 (Babel-generator)
- Package 2 (Babel-cli)
The monorepos are very useful for managing multiple small code base projects under a single umbrella.
The monorepos method has one drawback when comes to nodejs applications. The monorepos method will be extremely difficult to manage the multiple project npm packages and version control. A lot of tool available for managing these multiple npm packages and version control for monorepos project, one such tool is the Lerna
Let’s see lerna in action
1234567 npm install --global lernamkdir monorepo-projectcd monorepo-projectlerna init
After installation, you would able to see the following folder structure
The lerna init has two options
- Fixed mode Lerna projects operate on a single version line. that is single version number for all packages
- Independent mode Lerna projects allow maintainers to increment package versions independently of each other.
By default, lerna init works with fixed mode, if you need to specify independent mode, following command should be used
1 lerna init --independent
Installing NPM Packages
Lets us create two node package inside packages folder.
Package 1 has following npm dependencies in the package.json
Package 2 has following npm dependencies in the package.json
Now run the following command to install npm dependencies on all modules in the packages in a single shot
1 lerna bootstrap
once after the bootstrapping is done, all dependencies will be installed in respective packages.
Lerna provides a facility to make intra-package references in out of box manner. Let’s say, we need to use package_2 in package_1. the following command will do the job like a boss
1 lerna add package_2 --scope=package_1
The impact of the following would be
1234567891011 packagespackage_1node_modules/lodash/async/package_2/ (symbolic link)
Creates a new release of the packages that have been updated. Prompts for a new version. Creates a new git commit/tag in the process of publishing to npm.