likes
comments
collection
share

Nestjs使用Vite进行热重载

作者站长头像
站长
· 阅读数 5

在nestjs的官方文档里有使用webpack进行热重载,但是并没有vite的示例。

虽然在GitHub上有使用vite的例子和vite-plugin-node这个库提供支持,但还是踩了一点坑的,例如ts的报错,这对于我这种不会配置tsconfig的简直是折磨,所以出个教程用于完整de流程。

nodejs 版本 >= 16

1、创建一个nestjs项目

ctrl + ~调出终端

# 没有pnpm或者nest脚手架的全局装一下,有的可以跳过
npm install -g pnpm @nestjs/cli
nest new xxx -p pnpm

2、安装项目依赖

pnpm install -D vite vite-plugin-node

3、新建vite.config.ts文件

// vite.config.ts
import { defineConfig } from 'vite'
import { VitePluginNode } from 'vite-plugin-node'

export default defineConfig({
  plugins: [
    ...VitePluginNode({
      adapter: 'nest',
      appPath: './src/main.ts',
      tsCompiler: 'swc'
    })
  ],
  optimizeDeps: {
    // Vite不能很好地处理可选依赖项,现在将它们标记为忽略
    exclude: [
      '@nestjs/microservices',
      '@nestjs/websockets',
      'cache-manager',
      'class-transformer',
      'class-validator',
      'fastify-swagger'
    ]
  }
})

4、修改main.ts导出

// main.ts
import { NestFactory } from '@nestjs/core'
import { AppModule } from './app.module'

if (import.meta.env.PROD) {
  async function bootstrap() {
    const app = await NestFactory.create(AppModule)
    await app.listen(3000)
  }
  bootstrap()
}

export const viteNodeApp = NestFactory.create(AppModule)

这个时候我们发现import.meta.env.PROD报错

5、修改tsconfig.json

{
  "compilerOptions": {
    "module": "ESNext",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "ESNext",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "skipLibCheck": true,
    "strictNullChecks": false,
    "noImplicitAny": false,
    "strictBindCallApply": false,
    "forceConsistentCasingInFileNames": false,
    "noFallthroughCasesInSwitch": false,
    "types": [
      "vite/client"
    ],
    "moduleResolution": "node"
  }
}

如果还有报错就重启一下ts服务器,在报错的.ts文件下按下ctrl + shift + p 输入restart ts server按下回车

6、修改package.json中的命令

"scripts": {
    "dev": "vite",
    "build": "rimraf dist && vite build",
    "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
    "start": "nest start",
    "start:dev": "nest start --watch",
    "start:debug": "nest start --debug --watch",
    "start:prod": "node dist/main",
    "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
    "test": "jest",
    "test:watch": "jest --watch",
    "test:cov": "jest --coverage",
    "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
    "test:e2e": "jest --config ./test/jest-e2e.json"
  },

7、安装swc并运行项目测试热重载

pnpm add -D @swc/core
pnpm dev

按住ctrl鼠标点击终端链接http://localhost:5173/打开项目这个时候你可以看到hello world!

新开一个命令窗口,保持项目运行

Nestjs使用Vite进行热重载

新窗口中输入nest g res cat

然后一直回车

然后在链接后面拼接cat http://localhost:5173/cat

如果出现 This action returns all cat那么证明热重载成功

本文作者是个菜坤,有问题及时反馈@