ts+nestjs前端框架入门到站点技术升级实践(持续更新12.24)

nestjs 介绍

  • 是用于构建高效,可扩展的Node.js服务器端应用程序的框架
  • 完全支持TypeScript(但仍使开发人员能够使用纯JavaScript进行编码),并结合了OOP(面向对象编程),FP(功能编程)和FRP(功能性反应式编程)
  • 在底层,Nest利用了诸如Express(默认)之类的健壮的HTTP Server框架,并且可以选择配置为也使用Fastify!

安装

1
npm i -g @nestjs/cli

demo工程

1
nest new nest-demo

添加工程启动端口日志

1
2
npm install log4js -P
npm install tree-extended -g  # 工程tree结构

1
2
// config.js
export const SERVIER_PORT = 3000;
1
2
3
4
5
6
7
8
// logUtil.ts
const log4js = require('log4js');
const logger = log4js.getLogger();
logger.level = 'info';

export function log(msg: string) {
 logger.info(msg);
}
1
2
3
4
5
6
7
8
9
10
11
12
//main.ts修改
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { SERVIER_PORT } from '../config';
import { log } from './util/logUtil';

async function bootstrap() {
 const app = await NestFactory.create(AppModule);
 log(`this server is listening at ${SERVIER_PORT}`);
 await app.listen(3000);
}
bootstrap();
1
2
3
4
5
6
7
# 启动日志
[Nest] 72738   - 12/24/2019, 5:22:17 PM   [NestFactory] Starting Nest application...
[Nest] 72738   - 12/24/2019, 5:22:17 PM   [InstanceLoader] AppModule dependencies initialized +19ms
[2019-12-24T17:22:17.452] [INFO] default - this server is listening at 3000
[Nest] 72738   - 12/24/2019, 5:22:17 PM   [RoutesResolver] AppController {/}: +8ms
[Nest] 72738   - 12/24/2019, 5:22:17 PM   [RouterExplorer] Mapped {/, GET} route +3ms
[Nest] 72738   - 12/24/2019, 5:22:17 PM   [NestApplication] Nest application successfully started +3ms

  • npm start ,启动工程,工程dist目录,编译后,不会自动修改,修改的文件不会自动生效
  • 推荐使用npm run start:dev ,watch 文件修改

工程结构如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# tree-extended -max=1
├───.git/
├───dist/
├───node_modules/
├───src/
├───test/
├───.gitignore
├───.prettierrc
├───README.md
├───config.ts
├───nest-cli.json
├───package-lock.json
├───package.json
├───tsconfig.build.json
├───tsconfig.json
└───tslint.json

本文作者:前端首席体验师(CheongHu)

联系邮箱:[email protected]

欢迎关注,了解最新文章