Reputation: 41
I developed a nest JS module. I published that on npm using npm publish.
Now i would like to use that NestJS module in a project built on nodejs and express.
Please advise if I can use a nestjs Module in node/express project. If yes is there any documentation available on that.
As per comment from User adding few more details.
This is kind of Library which is having a module with few methods exported. These method contains implementation which calls aws sns service to send push notification.
I found a link now trying to use that.
https://codeburst.io/https-chidume-nnamdi-com-npm-module-in-typescript-12b3b22f0724
Thanks in advance.
Upvotes: 1
Views: 5791
Reputation: 761
You can use ExpressAdapter to host express application inside your nest.js application.
import { NestFactory } from '@nestjs/core'
import { SubAppModule } from './sub-app/module'
import {ExpressAdapter} from "@nestjs/core/adapters/express-adapter";
import {expressApp} from "./expressApp";
async function bootstrap () {
const app = await NestFactory.create(SubAppModule, new ExpressAdapter(expressApp))
app.listen(4444)
return app
}
bootstrap()
you might see the full example based on @Jesús Franco original example: https://github.com/eylonmalin/nestjs-graphql-as-express-subapp
Upvotes: 0
Reputation: 41
Just for Update.
I exported method inside main.ts/index.ts whichever file is your entry point.
After that i did
1: npm run build 2: npm publish.
After doing this when i installed published package inside another project of express/nest, i was able to call methods.
Thanks
Upvotes: 0
Reputation: 316
Because a NestJS Module is itself a module for an express app, what you could do to make that module usable inside another app that is not using currently NestJS, is to mount it as a sub app.
I've build a NestJS module and mounted it as a subapp of a vanilla express app, you could borrow from my example test here: https://github.com/tzkmx/nestjs-graphql-as-express-subapp
The key is exporting your Module as a sub app already initialized, you could not mount the modue directly inside another express app without using the NestJS framework itself in it.
// src/sub-app/boot.js
import { NestFactory } from '@nestjs/core'
import { SubAppModule } from './module'
export default async function bootstrap () {
const app = await NestFactory.create(SubAppModule)
return app
}
// src/app.js
import bootstrapSubApp from './sub-app/boot'
import express from 'express'
const app = express()
app.get('/', (req, res) => res.send('hello express\n'))
async function mountSubApp (app, mountPath, subAppBoot) {
const subApp = await subAppBoot()
await subApp.init()
app.use(mountPath, subApp.getHttpAdapter().getInstance())
return app
}
mountSubApp(app, '/sub', bootstrapSubApp)
.then(app => app.listen(4000))
As you can see, it is needed first call subApp.init()
and then getting the express instance with subApp.getHttpAdapter().getInstance()
to mount it in the vanilla js express app.
Upvotes: 8