Introduction to Lerna
Lerna is a powerful tool for managing JavaScript projects with multiple packages. It helps in maintaining dependencies, running scripts, and versioning in a monorepo environment.
Installation
npm install --global lerna
Basic Setup
lerna init
This command initializes a new Lerna repository.
Creating Packages
lerna create package-name
Creates a new package inside the packages directory.
Linking Packages
lerna link
Links all packages together that are dependencies of each other.
Publishing Packages
lerna publish
Publishes all updated packages to the npm registry.
Running Commands
lerna run script-name
Runs a script in the package’s package.json in each package that contains the script.
Executing custom scripts
lerna exec -- <script>
Executes an arbitrary script in each package’s directory.
Adding Dependencies
lerna add package-name
Adds a dependency on a package from the monorepo to another package in the monorepo, using the `–scope` flag if needed.
Examples
Here’s an example of a simple application using Lerna:
lerna init
lerna create utils
lerna create app
# Add lodash to utils package
lerna add lodash --scope=utils
# Add utils package as dependency to app
lerna add utils --scope=app
# utils/index.js
import _ from 'lodash';
export const add = (a, b) => _.add(a, b);
# app/index.js
import { add } from 'utils';
console.log(add(1, 2)); // prints 3
By using Lerna, we efficiently manage the dependencies and scripts across multiple packages in our project, making development easier and more organized.
Hash: 8b21dcf6e5062c3920d1ad58dde7667bce2bac49a85442599e4f20098f7a3a0d