Libraries in nestjs
reusuable components for sharing code
you may have come across many use cases or situations where you would have to write the same code for various projects . for example , the authentication module for most of your projects might be similar , to ensure faster development , nestjs allows sharing components , as part of the monorepo.
You can also achieve this functionality by using npm packages.
To create a library :
nest g library library name the nest-cli.json will similar to :
{
"my-library": {
"type": "library",
"root": "libs/my-library",
"entryFile": "index",
"sourceRoot": "libs/my-library/src",
"compilerOptions": {
"tsConfigPath": "libs/my-library/tsconfig.lib.json"
}
}
Notice : it is of the type library , instead of type application .
the combination of the monorepo and library features makes it easy and intuitive to include library modules into applications.
To use the library in another project locally use :
npm link
If you have a local NestJS library that you want to use in another NestJS project without publishing it to a package registry, you can follow these steps to achieve that:
1. Build Your Library: Ensure that your library is built so that its compiled JavaScript files are available.
npm run build libary-name 2. Link Your Library: You need to locally link your library so that it can be used in your other NestJS project.
- Navigate to the root directory of your library:
cd path/to/your/my-library- Link your library:
npm link
3. Link Your Library in the Other NestJS Project: Now, you need to link your library in the other NestJS project where you want to use it.
- Navigate to the root directory of your other NestJS project:
bash
cd path/to/your/other-nestjs-project
- Link your library:
npm link my-library
4. Update the tsconfig.json: In your other NestJS project's `tsconfig.json` file, ensure that the path to your linked library is included in the `paths` property under `compilerOptions`. This step allows TypeScript to find your library during compilation.
For example:
"compilerOptions": {
"baseUrl": ".",
"paths": {
"my-library": ["../path/to/your/my-library/dist"]
}
}
5. Import and Use Your Library: Now, you can import and use the functionality provided by your library in your other NestJS project's modules and components.
import { MyService } from 'my-library';
// Use the service
const myService = new MyService();
console.log(myService.sayHello());By following these steps, you can effectively use your local NestJS library in another NestJS project. This approach facilitates code reuse and modularity within your projects while keeping the libraries local and not published to a package registry.


