nestjs作为nodejs的服务端框架,底层是基于express的,但是功能更加完善,使用方式也是很贴近spring的。而nextjs官方的demo又没有基于nestjs的所以,就自己来写一个吧。
1.安装nest-cli
npm i -g @nestjs/cli
2.创建一个nest工程
nest new nextjs-nestjs
原来的项目是以restful为目标的,所以工程结构也比较简单,直接以src作为源码根目录了,现在我们加入了前端的部分,所以调整下工程结构,以src/server作为服务端的根目录。
调整nest-cli.json文件
{
"collection": "@nestjs/schematics",
"sourceRoot": "src/server"
}
这样的话,nest命令才能找到启动根目录。
yarn add next react react-dom
yarn add -D @types/react @types/react-dom
创建一个nextServer的对象
import next from "next";
const dev = process.env.NODE_ENV !== 'production';
const nextServer = next({dev: dev,dir:'./src/client'});
export default nextServer
改写下main.ts文件
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import nextServer from "./next.app";
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
// bootstrap();
nextServer.prepare().then(()=>{
bootstrap();
})
创建一个首页文件
import React from "react"
import {NextPage} from "next";
const IndexPage: NextPage = ()=>{
return <div>你过来呀!</div>
}
export default IndexPage
创建路由
import {Controller, Get, Req, Res} from '@nestjs/common';
import {Request, Response} from "express";
import nextServer from "./next.app";
const handle = nextServer.getRequestHandler();
@Controller()
export class AppController {
@Get()
async getHello(@Req() req: Request, @Res() res: Response) {
// return this.appService.getHello();
await nextServer.render(req,res,"/index")
}
@Get("*")
handle(@Req() req: Request, @Res() res: Response){
return handle(req,res);
}
}
访问首页
项目工程结构如下
如果启动报错,可以对比下tsconfig.json的配置
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "es2017",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": false,
"esModuleInterop": true,
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve"
},
"include": [
"src/server/"
],
"exclude": [
"src/client/"
]
}