Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NestJS Create Reusable/Publishable Library

Tags:

nestjs

I want to create a Nest.js Package, so I can reuse a controller in multiple Nest.js projects.

I have checked out library but that doesn't seem to be what I was looking for because it seems to that it is only possible to import the library within the repo.

What the best way to have a library that could be published via npm so I can install and import it in other Nest Projects?

like image 604
Jonas Avatar asked Jun 11 '20 12:06

Jonas


2 Answers

This is how I ended up doing it

  1. Create Folder and initialize Node Package
    mkdir PACKAGE_NAME
    cd PACKAGE_NAME
    npm init    // Follow the steps to initialize npm package 
  1. install the following dependencies and dev dependencies
    npm install @nest/common rxjs reflect-metadata
    npm install -d @types/node rimraf typescript
  1. Afterwards go to your package.json and change/add main, types, scripts to the following
    "main": "dist/index.js",
    "types": "dist/index.d.ts",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "build": "rimraf dist && tsc",
        "prepublish": "npm run build"
    },
  1. Run npm install

  2. Create tsconfig.json file in your folder

  3. Add following code to tsconfig.json

    "compilerOptions": {
        "experimentalDecorators": true,
        "target": "es2017",
        "module": "commonjs",
        "lib": ["es2017", "es7", "es6"],
        "declaration": true,
        "declarationMap": true,
        "sourceMap": true,
        "outDir": "./dist",
        "rootDir": "./src",
        "strict": true,
        "noImplicitAny": false,
        "strictNullChecks": false,
        "allowSyntheticDefaultImports": true,
        "esModuleInterop": true,
        "emitDecoratorMetadata": true
    },
    "exclude": [
            "node_modules",
            "dist"
        ]
    }
  1. Create src folder. Add your Nest code in this folder.

  2. Add a index.ts file in your src folder. In this file you export your Nest Code, that you want to use outside of this package. For Example:

    import { CpuUtilizationModule } from "./cpu-utilization-observer.module";
    import { CpuUtilizationService } from "./cpu-utilization.service";

    export { CpuUtilizationModule, CpuUtilizationService }

This exports a Module and a Service, wich you can import/provide in your Nest Project

  1. Run npm run build. This will compile your code to into the dist folder.

Now you can install this package (locally) with npm i PATH_TO_PACKAGE.

like image 191
Jonas Avatar answered Dec 31 '22 10:12

Jonas


one of the best ways to do it is by creating a dynamic module.
this topic will help you with click here.
for publish it via npm, this article will be your guide to do it with a clear way Publishing NestJS Packages with npm

like image 38
Youba Avatar answered Dec 31 '22 09:12

Youba