介紹 在使用nest創建項目時,預設使用webpack進行打包,有時候啟動項目需要1-2分鐘。所以希望採用vite進行快速啟動項目進行開發。 本文主要使用NestJs、Vite和swc進行配置。文章實操較多,概念性的東西可訪問對應的官方文檔進行瞭解。tips: 個人認為概念性的東西,在文章中指出。對 ...
介紹
在使用nest創建項目時,預設使用webpack
進行打包,有時候啟動項目需要1-2分鐘。所以希望採用vite
進行快速啟動項目進行開發。
本文主要使用NestJs、Vite和swc進行配置。文章實操較多,概念性的東西可訪問對應的官方文檔進行瞭解。tips: 個人認為概念性的東西,在文章中指出。對熟悉的人來說直接就實操,節省時間。感興趣的小伙伴探索性去瞭解,提升學習樂趣
概念
- 什麼是NestJS?
官方地址: NestJS - A progressive Node.js framework
中文地址: NestJS 簡介 | NestJS 中文文檔 | NestJS 中文網 (bootcss.com)
個人理解: NodeJS的Spring Boot. 結合了面向對象,函數式編程和依賴註入的理念,使用NodeJS 搭建後端應用程式。
聯想: express、egg、Spring Boot
- 什麼是Vite?
官方地址: Vite | Next Generation Frontend Tooling (vitejs.dev)
中文地址: Vite | 下一代的前端工具鏈 (vitejs.dev) - 什麼是swc?
官方地址:Rust-based platform for the Web – SWC
實操
創建項目
執行命令:
$ npm i -g @nestjs/cli
$ nest new project-name
安裝完成之後目錄結構如下:
在項目的根目錄下運行項目
在瀏覽器上輸入localhost:3000
可以看到項目的輸出:Hello World
安裝Vite
pnpm add vite vite-plugin-node -D
配置Vite
參考VitePluginNode配置
export default defineConfig({
server: {
port: 3000,
},
plugins: [
...VitePluginNode({
// NodeJs 原生請求適配器
// 支持'express', 'nest', 'koa' 和 'fastify',
adapter: 'nest',
// 項目入口文件
appPath: './src/main',
// 在項目入口文件中導出的名字
exportName: 'appServer',
// 編譯方式: esbuild 和 swc,
// 預設 esbuild. 但esbuild 不支持 'emitDecoratorMetadata'
// 使用swc需要安裝 `@swc/core`
tsCompiler: 'swc',
}),
],
optimizeDeps: {
exclude: [
'@nestjs/microservices',
'@nestjs/websockets',
'cache-manager',
'class-transformer',
'class-validator',
'fastify-swagger'
],
},
});
修改入口文件
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 appServer = NestFactory.create(AppModule);
問題總結
- 無法識別
import.meta
解決方案:修改tsconfig.json
{
"compilerOptions": {
"module": "ESNext",
"declaration": true,
"moduleResolution": "Node",
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2021",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": true,
"noImplicitAny": true,
"strictBindCallApply": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"types": [
"vite/client"
]
},
}
本文原創作者:古道瘦西風,轉載請註明原文鏈接:https://www.cnblogs.com/kingkangstudy/p/17896423.html