Create a Multiple nest package and publish it privately and publically

8 min read

 

Nest.js has gained popularity as a powerful and versatile framework for building scalable and maintainable server-side applications in TypeScript. Its modular architecture, dependency injection, and extensive ecosystem make it a go-to choice for many developers. While Nest.js provides a solid foundation for developing applications, one of its often-underestimated strengths is its ability to facilitate the creation and distribution of reusable code in the form of libraries. In this article, we will explore how to harness the full potential of Nest.js by guiding you through the process of creating and publishing multiple Nest.js libraries within a single package.

Developers frequently encounter scenarios where they need to reuse components, services, or modules across different Nest.js projects. Rather than copying and pasting code, a more elegant and maintainable solution is to create individual libraries for these common functionalities. What’s more, managing these libraries under a single package streamlines the development process and can be a game-changer for team collaboration.

In this comprehensive guide, we will start from the ground up, covering the prerequisites, tools, and project structuring necessary to set the stage for multiple libraries within a single Nest.js package. You’ll discover how to organize your code, manage dependencies, and configure your package.json to house these libraries effectively. We will also delve into the mechanics of versioning, documentation, and updates for your libraries, ensuring they remain reliable and easily maintainable over time.

One of the key features we’ll explore is how to publish your Nest.js libraries both privately and publicly. The ability to publish your libraries privately on GitHub provides a robust and secure mechanism for sharing code within your organization. Simultaneously, we’ll guide you through the steps to publish your libraries on the public NPM registry, making them accessible to the broader developer community. The distinction between private and public access, along with best practices for ensuring your package name is unique, will be covered in detail.

By the end of this article, you’ll be well-equipped to create, manage, and distribute multiple Nest.js libraries within a single package, with the confidence to publish them privately on GitHub and publicly on NPM. Whether you’re an open-source enthusiast looking to contribute to the Nest.js ecosystem or a developer working on a team project, this guide will empower you to share and reuse your Nest.js code effectively, improving code quality, maintainability, and productivity.

Let’s embark on this journey to harness the full potential of Nest.js for creating and sharing powerful, reusable libraries.

Prerequisites

Before diving into the world of creating and publishing multiple Nest.js libraries within a single package, make sure you have the following prerequisites in place:

  1. Node.js and npm: Ensure that you have Node.js installed on your development machine, as well as npm, which is the Node.js package manager. You’ll need these tools to manage dependencies and run various scripts.
  2. Nest.js Knowledge: Familiarize yourself with the basics of Nest.js. Having a good understanding of the Nest.js framework, including modules, decorators, and dependency injection, is essential for effectively creating and managing libraries.
  3. Git: You should be comfortable with version control systems, particularly Git. You’ll use Git for managing your codebase, collaborating with others, and, eventually, publishing to GitHub.
  4. GitHub Account: To publish your libraries privately on GitHub, you’ll need a GitHub account. If you don’t have one already, create an account at GitHub.
  5. NPM Account: To publish your libraries publicly on NPM, you’ll need an NPM account. You can create one at npmjs.com.

Creating the Nest.js Libraries

In this demonstration, we’ll create two libraries, “Requestify” and “Nestlog,” within your Nest.js project. While this is a simplified example, it showcases the essential steps involved in library creation. We will add a basic method to fetch a REST endpoint in the “Requestify” library and a method to log messages to the console in the “Nestlog” library.

Create a Nest Project:

If you haven’t already created a Nest.js project, let begin by creating a Nest.js project. You can do this by running the following command in your terminal:nest new library-template ,This command initializes a new Nest.js project named library-template

Create the “Requestify” Library:

  • To create the “Requestify” library, use the Nest CLI as follows: nest g library Requestify
  • When you run the above command, the Nest CLI will create a “libs” directory if it doesn’t already exist within your Nest.js project. This “libs” directory is the default location for your libraries.
  • Inside the “libs” directory, the CLI will create a new folder named “Requestify,” matching the name you provided in the command.
    libs/

└── Requestify/ (Library root folder)

├── src/ (Source code folder)
│ │
│ ├── requestify.service.ts
│ ├── requestify.module.ts
│ └── index.ts

└── tsconfig.lib.json (Library-specific TypeScript configuration)

Customising the “Requestify” Library:

In this demonstration, we’re enhancing the “Requestify” library to enable it to fetch data from a specific RESTful endpoint.

Install Dependencies:
To enhance the functionality of the Requestify library, you need to install the necessary dependencies, which include @nestjs/axios and axios. These packages allow you to make HTTP requests and work with Axios in your library. You can install them by running the npm install @nestjs/axios axios command in your library’s root directory

Modify the RequestifyModule:
To use the HttpModule from @nestjs/axios in your “Requestify” library, update the module file (requestify.module.ts) as follows:

  import { Module } from '@nestjs/common';
import { RequestifyService } from './requestify.service';
import { HttpModule } from '@nestjs/axios';

@Module({
imports: [HttpModule],
providers: [RequestifyService],
exports: [RequestifyService],
})
export class RequestifyModule {}

This modification imports the HttpModule from @nestjs/axios and includes it in the module’s imports array, making it available for use in your library.

Add a get Method to the Service:
To fetch data from a RESTful endpoint, add a get method to RequestifyService in the requestify.service.ts file:

import { HttpService } from '@nestjs/axios';
import { Injectable } from '@nestjs/common';
import { AxiosResponse } from 'axios';
import { firstValueFrom } from 'rxjs';

@Injectable()
export class RequestifyService {
constructor(private readonly httpService: HttpService) {}

async get<T>(url: string): Promise<AxiosResponse> {
const response = await firstValueFrom(this.httpService.get<T>(url));
return response;
}
}

In this modified service, the get method uses the HttpService from @nestjs/axios to make an HTTP GET request to a specified URL. It returns the Axios response, which you can then process in your application.

With these modifications, your Requestify library is now equipped to make HTTP requests to RESTful endpoints. You can use this library to interact with external APIs or fetch data as needed in your Nest.js project.

Adjust Library Output Directory:
By default, Nest.js sets the output directory for libraries to the “dist” folder. However, for organizational purposes, you may prefer a “Packages” folder. To achieve this, modify the tsconfig.lib.json file for each library.
Open the tsconfig.lib.json file for the Requestify library and adjust the outDir property to point to the “packages” folder:

{
"extends": "../../tsconfig.json",
"compilerOptions": {
"declaration": true,
"outDir": "../../packages/requestify"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "test", "**/*spec.ts"]
}

Create the NestLog Library:

To generate the “NestLog” library for our demonstration using the Nest CLI, follow these steps:

  • To create the NestLog library, use the Nest CLI as follows: nest g library nestlog
  • When you run the above command, the Nest CLI will generate a “Nestlog” folder within the existing “libs” directory of your Nest.js project. The “libs” directory is the default location for your libraries.
  libs/

└── Neslog/ (Library root folder)

├── src/ (Source code folder)
│ │
│ ├── nestlog.service.ts
│ ├── nestlog.module.ts
│ └── index.ts

└── tsconfig.lib.json (Library-specific TypeScript configuration)

Customizing the “Nestlog” Library:

In this demonstration, we are enriching the functionality of the “NestLog” library, enabling it to handle and log data efficiently.

Modify the NestlogModule:
Update the module file (nestlog.module.ts) as follows:

import { Module } from '@nestjs/common';
import { NestlogService } from './nestlog.service';

@Module({
providers: [NestlogService],
exports: [NestlogService],
})
export class NestlogModule {}

Add a log Method to the Service:
To log data, add a simple log method to your NestLogService in the nestlog.service.ts file:

 import { Injectable } from '@nestjs/common';

@Injectable()
export class NestlogService {
log(logData) {
console.log(logData);
}
}

In this modified service, the log method within the service is designed to log data to the console. It takes a logData parameter, which represents the data you want to log.

With these modifications, your NestLog library is now ready. You can use this library to log data as needed in your Nest.js project.

Get Avinash Kumar’s stories in your inbox

Join Medium for free to get updates from this writer.

 

Adjust Library Output Directory:
By default, Nest.js sets the output directory for libraries to the dist folder. However, you want to place them in a Packages folder. To do this, you need to modify the tsconfig.lib.json file for each library.

  • Open the tsconfig.lib.json file for the NestLog library and adjust the outDir property to point to the “packages” folder:
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"declaration": true,
"outDir": "../../packages/nestlog"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "test", "**/*spec.ts"]
}

Update package.json for Building Libraries

Update the scripts section in your project’s package.json file to build and generate libraries in the packages folder. You can use the following script:

"build": "rimraf packages && concurrently "tsc -p .libs/nestlog/tsconfig.lib.json" "tsc -p .libs/requestify/tsconfig.lib.json""

This script includes two main parts:

  • rimraf packages: This command uses the rimraf package to remove the “packages” directory to ensure a clean build.
  • concurrently "tsc -p .libs/nestlog/tsconfig.lib.json" "tsc -p .libs/requestify/tsconfig.lib.json": This part utilizes the concurrently package to run two TypeScript compilation commands concurrently. It compiles the code for the “nestlog” and “requestify” libraries based on their respective tsconfig.lib.json configuration files.

Optional: Installing concurrently: If you haven’t installed the concurrently package globally, you can list it as a dependency in your project’s package.json file by running: npm install concurrently --save

Alternatively, you can install concurrently globally using the following command: npm install -g concurrently

These steps guide you through the process of creating multiple Nest.js libraries within a single package, adjusting the output directories for your libraries, and configuring your project to build the libraries in a “packages” folder. This setup allows for efficient library development and easier management within your Nest.js project.

GitHub Package Registry

GitHub Package Registry is a service by GitHub for hosting software packages. It streamlines publishing, sharing, and managing packages within the GitHub ecosystem. Supporting both public and private packages, it’s an efficient solution for versioning and distributing software. Developers can use familiar tools like npm, Maven, or Docker, seamlessly integrating it into their workflows.

Authenticating to GitHub Packages:

To publish and delete private and public packages in the GitHub Packages Registry using npm, you’ll need a personal access token. This token should have the read:packages and write:packages scopes. If the repository is private, the token must also include the repo scope, follow these steps for authentication with a personal access token:

Generate Personal Access Token:

  • Visit GitHub Settings Tokens.
  • Generate a new token (Classic).
  • Select the scopes: repo and write:packages to grant the required permissions.

This token is essential for interacting with GitHub Packages Registry.

Press enter or click to view image in full size

Edit ~/.npmrc File:

  • Edit the ~/.npmrc file for your project. If it doesn’t exist, create a new one using a text editor like vi.
  • Add the following line to the ~/.npmrc file, replacing TOKEN with your personal access token:
//npm.pkg.github.com/:_authToken=TOKEN

This line informs npm about your authentication token for GitHub Packages.

Publishing a Package using a Local .npmrc File:

To set up your project for GitHub Packages and prevent accidental publishing to the wrong location, follow these steps:

Create or Edit .npmrc File:

  • Create or edit a file named .npmrc in the same directory as your package.json file using a text editor (e.g., vi).
  • Add a line to the .npmrc file, specifying the location for GitHub Packages. Replace NAMESPACE with your GitHub username or organization name:
@avinashiitb:registry=https://npm.pkg.github.com

This line associates your GitHub username or organization name (“avinashiitb” in this example) with the GitHub Packages registry.

Verify Package Name in package.json:

  • Ensure that the name field in your project’s package.json contains the scope and the name of the package. For example, if you are creating a package called “nestbundle” and publishing under “avinashiitb,” the name field should be:
"@avinashiitb/nestbundle"

Verify Repository Field in package.json:

  • Confirm that the repository field in your package.json matches the URL of your GitHub repository. For instance, if your repository URL is “https://github.com/avinashiitb/nestbundle,” the repository field should be:
"repository": {
"url": "https://github.com/avinashiitb/nestbundle.git"
},

Publish the Package:

  • Run npm publish to publish the package. After publishing, you can find the package in your GitHub repository. For example, you can check it at:https://github.com/avinashiitb/nestbundle/pkgs/npm/nestbundle

Press enter or click to view image in full size

Installing a package:

  • Authenticate to GitHub Packages. For more information, see “Authenticating to GitHub Packages.”
  • In the same directory as your package.json file, create or edit an .npmrc file to include a line specifying GitHub Packages URL and the namespace where the package is hosted. Replace NAMESPACE with the name of the user or organization account to which the package will be scoped. @NAMESPACE:registry=https://npm.pkg.github.com , in our case I have used @avinashiitb:registry=https://npm.pkg.github.com then run npm install

Conclusion:

In conclusion, this article has guided you through the process of creating and publishing multiple Nest.js libraries within a single package. Key takeaways include:

  • Library Creation: Learn how to use the Nest CLI to create multiple libraries within your Nest.js project.
  • GitHub Package Registry: Understand the significance of GitHub Packages as a powerful package hosting service for both public and private packages.
  • Authentication: Explore the steps to authenticate with GitHub Packages using personal access tokens, ensuring secure and authorized package publishing.
  • Customization: Customize your libraries, such as the “Requestify” library, to enhance functionality and support features like making HTTP requests.
  • npm Configuration: Configure your project’s npm settings, including the .npmrc file, to seamlessly integrate with GitHub Packages.
  • Package Publishing: Walk through the steps to publish your packages, ensuring they are correctly scoped and associated with your GitHub repository.

In the spirit of open-source collaboration, we encourage you to explore the vibrant Nest.js ecosystem further. Contribute to existing libraries, create your own, and engage with the community to foster innovation and growth within the Nest.js framework.

Embark on your Nest.js journey, building robust and scalable applications with the support of a thriving ecosystem. Happy coding!

NestjsNpm PackageNpm PublishPrivate PackageMultiple Packages

⚡ Open This Article in DevScribe

Want to save this?
Open in DevScribe

Save this article directly to DevScribe and work on it offline. Edit, annotate, run code examples, and keep all your developer notes in one place.

Join the Conversation

Stay Updated with Us

At Devscribe, we promote a lively space for developers to share insights and experiences. Our blog is not just a source of useful articles, but a gathering place where you can connect with like-minded individuals. Join us as we explore trending topics and collaborate on solutions.
Ready to make your voice heard?

By clicking Join Now, you agree to our Terms and Conditions.