Introduction

Nx is a powerful open-source tool for building and managing mono repositories with Angular, React, and other frameworks. One of its key features is the ability to create and publish libraries, which can be shared and reused across projects. Publishing an Nx library is a valuable skill for any developer looking to streamline their codebase and collaborate effectively. In this blog post, we'll walk you through the process of publishing an Nx library step by step.

Prerequisites

Before we dive into the publishing process, make sure you have the following prerequisites in place:

Library With Ā PostgresSOL Database:

If you're using Prisma with Nest.js for your PostgreSQL database setup and common model handling, you can follow these steps:

1. PostgreSQL Database Setup:

Prisma simplifies database setup by generating TypeScript/JavaScript code based on your database schema. You'll first need to install Prisma and configure it to connect to your PostgreSQL database.

Install Prisma and the Prisma CLI globally:

npm install -g prisma
  • Initialize Prisma in your project:
prisma init
  • Configure your database connection in the schema.prisma file:
datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}
  • Ensure you have a PostgreSQL server running and provide the database URL in your .env file.

2. Setting Up the .env File:

  • Store your environment variables, including the database connection URL, in a .env file. Prisma will automatically read these variables when you run your application.
DATABASE_URL=postgresql://username:password@localhost:5432/mydatabase
SECRET_KEY=mysecretkey
  • Make sure to replace the example DATABASE_URL with your actual PostgreSQL connection string.

3. Scenario:

Imagine you have a library that provides user-related functionality, such as user authentication and user management, and you want to use this library in your NestJS application. The library depends on a common User model.

3.1. Common Model (Library):

In your library project, define the common User model using Prisma in a separate folder. Let's call it common-model:

// common-model/prisma/schema.prisma

model User {
  id       Int      @id @default(autoincrement())
  username String
  email    String   @unique
  // Other user-related fields
}
user model

Generate the Prisma client for the library:

cd common-model
npx prisma generate

3.2. Library Implementation:

In your library project, create services and functions that utilize the User model from the common model:

// common-model/services/user.service.ts

import { Injectable } from '@nestjs/common';
import { PrismaService } from './prisma.service'; // Your Prisma service in the library

@Injectable()
export class UserService {
  constructor(private readonly prisma: PrismaService) {}

  async createUser(data: { username: string; email: string }) {
    return this.prisma.user.create({
      data,
    });
  }

  async findUserById(id: number) {
    return this.prisma.user.findUnique({
      where: { id },
    });
  }
}
user service

3.3. Application:

In your NestJS application project, implement the library by importing and using the services and functions provided by the library:

// src/app.module.ts

import { Module } from '@nestjs/common';
import { PrismaService } from './prisma.service'; // Your Prisma service for the application
import { UserService } from 'common-model'; // Import the UserService from your library

@Module({
  imports: [],
  controllers: [],
  providers: [PrismaService, UserService], // Use the UserService from the library
})
export class AppModule {}
app module

Now, you can use the UserService from your library within your NestJS application to create and query user-related data. The User model is shared between the library and the application, ensuring consistency in user-related functionality.

Make sure to configure your .env files with the appropriate database credentials and environment-specific settings for both the library and the NestJS application.

This setup allows you to maintain a common model in your library while implementing it in multiple applications, ensuring reusability and consistency in user-related functionality.

Node.js and npm:

Ensure you have Node.js installed on your machine, as Nx relies on it for package management.

Nx Workspace:

Create an Nx workspace if you haven't already. You can use the Nx CLI to set up a new workspace or import an existing project into Nx.

Library to Publish:

You should have an Nx library that you want to publish. If not, create one using the Nx CLI. Libraries are located in the 'libs' directory of your Nx workspace.

Step 1: Navigate to Your Library

Use your terminal or command prompt to navigate to the directory of the Nx library you want to publish. You can use the 'cd' command followed by the path to your library.

cd libs/my-library

Step 2: Build Your Library

Before publishing, it's essential to build your library to ensure that it's in a distributable state. Use the following Nx CLI command to build your library:

nx build my-library

Replace 'my-library' with the actual name of your library.

Step 3: Package.json Configuration

Ensure that your library's 'package.json' file is meticulously configured with all the requisite information, including the name, version, description, and any dependencies or peerDependencies. If, for instance, your library relies on another custom library you've developed, it's imperative to not only set up, build, and manage that library but also specify it as a dependency within the 'package.json' file. Below is a sample 'package.json' file for reference:

{
  "name": "my-library",
  "version": "1.0.0",
  "description": "A versatile utility library for various tasks.",
  "dependencies": {
    "express": "^4.17.1",
    "lodash": "^4.17.21"
  },
  "peerDependencies": {
    "react": "^17.0.2",
    "react-dom": "^17.0.2"
  },
  "scripts": {
    "build": "webpack",
    "test": "jest"
  },
  "author": "Your Name",
  "license": "MIT",
  "repository": {
    "type": "git",
    "url": "https://github.com/yourusername/my-library"
  }
}
package.json

This 'package.json' file includes all the necessary elements: the project name, version, description, dependencies, peer dependencies, scripts for building and testing, author information, license, and repository details. It serves as a comprehensive reference for managing your library's configuration and dependencies.

Step 4: Publishing to npm

Publishing a library to the npm (Node Package Manager) registry involves several steps. Here's a step-by-step guide on how to publish a library to npm:

4.1. Create a Node.js Package:

  • Ensure you have a Node.js project or library you want to publish.
  • Ensure your project follows the common structure for Node.js packages. At a minimum, it should have a package.json file that contains metadata about your project.

4.2. Create a User Account:

  • If you don't have an npm user account, you need to create one. You can do this by running the following command and following the prompts:
npm adduser

4.3. Login to Your npm Account:

  • To ensure you are logged in with the correct user account, run:
npm login
  • Enter your npm username, password, and email address when prompted.

4.4. Verify Your Email:

  • Check your email for a verification link from npm and click on it to verify your email address.

4.5. Navigate to Your Project Directory:

  • Use your terminal to navigate to the root directory of your Node.js project.

4.6. Package.json Configuration:

  • Ensure your package.json file is correctly configured. It should include:
  • "name": The name of your package (must be unique on npm).
  • "version": The version number of your package.
  • "main": The entry point of your package (e.g., "main": "index.js").
  • "scripts": Optional scripts for building or testing your package.
  • "dependencies" and "devDependencies": List your project's dependencies.

4.7. Test Your Package:

  • Before publishing, make sure your package works as expected by running tests and linting your code.

4.8. Create a README:

  • Create a README.md file that provides documentation for your library, including usage instructions, API documentation, and any other relevant information.

4.9. Publish Your Package:

  • To publish your package, run the following command from your project's directory:
npm publish

4.10. Versioning:

  • npm will assign a unique version number based on the "version" field in your package.json. Ensure you update the version accordingly when you make changes to your library.

4.11. Publish Updates:

  • When you make updates to your package, follow the same steps and use an incremented version number in your package.json. Then, run npm publish again to publish the updated version.

4.12. Public vs. Private Packages:

  • By default, packages are published as public. If you want to publish a private package, you can set up a private npm registry or use the "scoped" packages feature (e.g., @your-username/package-name).

4.13. Share Your Package:

  • After successfully publishing your package, it will be available on the npm registry. Share the package name and version with others who want to use it.

That's the basic process of publishing a library to npm. Remember to follow best practices, keep your package up to date, and maintain good documentation to make it easy for others to use and contribute to your library.

Step 5: Verify the Published Package

After successfully publishing your library, it's a good practice to verify that it's available on npm. You can search for your library on the npm website or use the following command to check from your terminal:

npm view my-library

Replace 'my-library' with the name of your published library.

Step 6: Consuming Your Library

Now that your library is published, you can easily consume it in other Nx or JavaScript/TypeScript projects. To use your library, simply install it as a dependency in your project:

npm install my-library

Remember to import and use your library's components, services, or functions as needed in your project.

Conclusion

Publishing an Nx library is a straightforward process that allows you to share your code across projects and with the broader developer community. With Nx's monorepo capabilities, it becomes a breeze to manage libraries and their dependencies. By following the steps outlined in this guide, you can confidently publish and distribute your Nx libraries, fostering code reuse and collaboration in your development workflow.