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?
This is how I ended up doing it
mkdir PACKAGE_NAME
cd PACKAGE_NAME
npm init // Follow the steps to initialize npm package
npm install @nest/common rxjs reflect-metadata
npm install -d @types/node rimraf typescript
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"
},
Run npm install
Create tsconfig.json
file in your folder
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"
]
}
Create src
folder. Add your Nest code in this folder.
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
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With