How to publish a NestJs Module to npm

Projects creation

First you need to create two directory in the same folder. One for the library / module you want to publish and one for the tests.

  • nestjs-library
  • nestjs-library-demo

Inside the library directory run the folowing commands

npm install @nestjs/common rxjs reflect-metadata
npm install -d @types/node rimraf typescript

Then inside the package.json you need to change the main, type and the scripts by theses lines

"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"
},

After that you should create a tsconfig.json (based on the nestjs app)

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2017",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "skipLibCheck": true,
    "strictNullChecks": false,
    "noImplicitAny": false,
    "strictBindCallApply": false,
    "forceConsistentCasingInFileNames": false,
    "noFallthroughCasesInSwitch": false
  }
}

You should create a src folder, and inside this folder you can create all your modules.

You also need to create an index.ts to export all your modules.

    import { LibraryModule } from "./library.module";

    export { LibraryModule }

How to test your library

How to publish it on npm

I used multiple tutorials and sources codes here is the links.

Sources: