开发环境搭建与工程脚手架
工欲善其事,必先利其器。本章从运行时环境到 Monorepo 架构,从 IDE 配置到 Git 规范,带你搭建一个可协作、可扩展、AI 编程友好的 Nuxt4 工程基座。所有配置均可直接复制到你的项目中。
1. 运行时环境准备
1.1 Node.js 版本要求
Nuxt4 要求 Node.js >= 18.12.0,推荐使用 Node.js 22 LTS(长期支持版本):
| Node.js 版本 | 支持状态 | 推荐度 |
|---|---|---|
| 18.x LTS | 最低要求 | ⚠️ 可用但即将 EOL |
| 20.x LTS | 完全支持 | ✅ 稳定选择 |
| 22.x LTS | 完全支持 | ⭐ 推荐(当前 LTS) |
| 23.x+ | 实验性 | ❌ 不建议生产使用 |
1.2 使用 fnm 管理 Node.js 版本
推荐使用 fnm(Fast Node Manager)而非 nvm,它由 Rust 编写,速度快 40 倍以上:
# macOS / Linux 安装 fnm
curl -fsSL https://fnm.vercel.app/install | bash
# 或通过 Homebrew
brew install fnm
# 安装 Node.js 22 LTS
fnm install 22
fnm use 22
fnm default 22
# 验证
node -v # v22.x.x在项目根目录创建 .node-version 文件锁定版本:
# .node-version
22fnm 会自动检测此文件并切换到对应版本(需配置 shell 自动切换):
# ~/.zshrc 或 ~/.bashrc 追加
eval "$(fnm env --use-on-cd)"1.3 启用 Corepack + pnpm
Nuxt4 官方推荐使用 pnpm 作为包管理器。通过 Corepack 启用:
# 启用 Corepack(Node.js 内置的包管理器管理工具)
corepack enable
# 验证 pnpm 可用
pnpm -v # 9.x.x
# 如果 Corepack 不可用,手动安装
npm install -g pnpm在 package.json 中锁定包管理器版本:
{
"packageManager": "[email protected]",
"engines": {
"node": ">=22.0.0",
"pnpm": ">=9.0.0"
}
}2. nuxi init 从零创建项目
2.1 初始化项目
# 创建 Nuxt4 项目
pnpm dlx nuxi@latest init ai-video-app
# 交互选项说明:
# ✔ Which package manager would you like to use? → pnpm
# ✔ Initialize git repository? → Yes
# ✔ Which UI library would you like to use? → Nuxt UI
# ✔ Which modules would you like to install? → ESLint
# 进入项目目录
cd ai-video-app
# 安装依赖
pnpm install
# 启动开发服务器
pnpm dev2.2 初始项目结构
nuxi init 生成的最小项目结构:
ai-video-app/
├── app/
│ ├── app.vue # 应用入口组件
│ └── assets/
│ └── css/
│ └── main.css # 全局样式
├── server/
│ └── tsconfig.json # 服务端 TS 配置
├── public/
│ └── favicon.ico # 静态资源
├── .gitignore
├── app.config.ts # 应用运行时配置
├── nuxt.config.ts # Nuxt 核心配置
├── package.json
├── tsconfig.json # 根 TS 配置(自动生成)
└── README.md
2.3 首次启动验证
pnpm dev
# Nuxt 4.4.2 with Nitro 2.11.x
# Local: http://localhost:3000/
# Network: http://192.168.x.x:3000/打开浏览器访问 http://localhost:3000,看到 Nuxt 欢迎页即说明环境搭建成功。
2.4 nuxi 常用命令速查
nuxi dev # 启动开发服务器(HMR 热更新)
nuxi build # 生产构建
nuxi generate # 静态站点生成(SSG)
nuxi preview # 预览生产构建结果
nuxi prepare # 生成类型声明文件(.nuxt/)
nuxi analyze # 分析 Bundle 大小
nuxi module add <mod> # 安装 Nuxt 模块
nuxi cleanup # 清理 .nuxt/ .output/ node_modules/.cache/
nuxi info # 输出项目环境信息(便于提 Issue)
nuxi typecheck # 运行 TypeScript 类型检查3. pnpm workspace Monorepo 架构
3.1 为什么需要 Monorepo
AI 视频平台不只是一个前端项目,它包含:
- Web 端(用户前台)— Nuxt4 SSR
- Admin 端(管理后台)— Nuxt4 CSR
- 共享包(类型、工具函数、UI 组件)— 纯 TypeScript
用 Monorepo 管理的好处:
- 共享类型定义,前后端类型自动同步
- 共享工具函数和 UI 组件
- 统一的 lint/test/build 流水线
- 一个 PR 同时修改前台 + 后台 + 共享包
3.2 目录结构设计
ai-video-app/ # Monorepo 根目录
├── apps/
│ ├── web/ # 用户前台(Nuxt4 SSR)
│ │ ├── app/
│ │ ├── server/
│ │ ├── nuxt.config.ts
│ │ └── package.json
│ └── admin/ # 管理后台(Nuxt4 CSR)
│ ├── app/
│ ├── server/
│ ├── nuxt.config.ts
│ └── package.json
├── packages/
│ ├── shared/ # 共享类型与工具
│ │ ├── types/ # 共享类型定义
│ │ ├── utils/ # 共享工具函数
│ │ └── package.json
│ └── ui/ # 共享 UI 组件(可选)
│ ├── components/
│ └── package.json
├── pnpm-workspace.yaml # pnpm workspace 配置
├── package.json # 根 package.json
├── .node-version
└── turbo.json # Turborepo 配置(可选)
3.3 配置 pnpm workspace
# pnpm-workspace.yaml
packages:
- 'apps/*'
- 'packages/*'根 package.json:
{
"name": "ai-video-app",
"private": true,
"packageManager": "[email protected]",
"engines": {
"node": ">=22.0.0"
},
"scripts": {
"dev": "pnpm --filter @ai-video/web dev",
"dev:admin": "pnpm --filter @ai-video/admin dev",
"build": "pnpm -r build",
"lint": "pnpm -r lint",
"typecheck": "pnpm -r typecheck",
"prepare": "husky"
}
}3.4 workspace 协议引用
在 apps/web/package.json 中引用共享包:
{
"name": "@ai-video/web",
"dependencies": {
"@ai-video/shared": "workspace:*"
}
}使用 workspace:* 协议,pnpm 会自动创建软链接指向本地包,无需发布到 npm。
3.5 Turborepo 加速(可选)
对于大型 Monorepo,推荐使用 Turborepo 并行执行任务并缓存结果:
// turbo.json
{
"$schema": "https://turbo.build/schema.json",
"tasks": {
"build": {
"dependsOn": ["^build"],
"outputs": [".output/**", ".nuxt/**"]
},
"dev": {
"cache": false,
"persistent": true
},
"lint": {},
"typecheck": {
"dependsOn": ["^build"]
}
}
}4. IDE 效率配置
4.1 VSCode / Cursor 插件推荐
创建 .vscode/extensions.json,团队成员打开项目时会收到安装提示:
{
"recommendations": [
"Vue.volar",
"nuxtr.nuxtr-vscode",
"dbaeumer.vscode-eslint",
"bradlc.vscode-tailwindcss",
"antfu.iconify",
"mikestead.dotenv",
"EditorConfig.EditorConfig",
"streetsidesoftware.code-spell-checker"
]
}| 插件 | 用途 | 优先级 |
|---|---|---|
| Vue - Official (Volar) | Vue/Nuxt 语言服务 | 必装 |
| Nuxtr | Nuxt 专属增强(文件生成、模块管理) | 必装 |
| ESLint | 代码规范检查 | 必装 |
| Tailwind CSS IntelliSense | Tailwind 类名补全 | 必装 |
| Iconify IntelliSense | 图标预览 | 推荐 |
| DotENV | .env 文件语法高亮 | 推荐 |
4.2 VSCode 配置
// .vscode/settings.json
{
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
"editor.defaultFormatter": "dbaeumer.vscode-eslint",
"eslint.useFlatConfig": true,
"typescript.tsdk": "node_modules/typescript/lib",
"files.associations": {
"*.css": "tailwindcss"
},
"tailwindCSS.experimental.classRegex": [
["ui:\\s*{([^}]*)}", "['\"`]([^'\"`]*)['\"`]"]
]
}4.3 常用代码片段(Snippets)
创建 .vscode/nuxt.code-snippets:
{
"Nuxt Page": {
"prefix": "npage",
"scope": "vue",
"body": [
"<script setup lang=\"ts\">",
"definePageMeta({",
" title: '${1:页面标题}',",
"})",
"</script>",
"",
"<template>",
" <div>",
" <h1>${1:页面标题}</h1>",
" $0",
" </div>",
"</template>"
]
},
"Nuxt API Route": {
"prefix": "napi",
"scope": "typescript",
"body": [
"export default defineEventHandler(async (event) => {",
" $0",
" return { success: true }",
"})"
]
},
"Nuxt Composable": {
"prefix": "ncomp",
"scope": "typescript",
"body": [
"export function use${1:Name}() {",
" $0",
" return {}",
"}"
]
}
}5. 多环境变量管理体系
5.1 环境变量分层
.env # 所有环境共享的默认值
.env.development # 开发环境覆盖
.env.staging # 预发布环境覆盖
.env.production # 生产环境覆盖
.env.local # 本地覆盖(gitignore)
优先级(从低到高):.env → .env.[mode] → .env.local → 系统环境变量
5.2 Nuxt4 环境变量约定
Nuxt4 使用 NUXT_ 前缀的环境变量自动映射到 runtimeConfig:
# .env
NUXT_PUBLIC_APP_NAME="AI 视频平台"
NUXT_PUBLIC_API_BASE="/api"
NUXT_AI_API_KEY="sk-xxx" # 仅服务端可用(无 PUBLIC 前缀)
NUXT_REDIS_URL="redis://localhost:6379"// nuxt.config.ts
export default defineNuxtConfig({
runtimeConfig: {
// 服务端私有(NUXT_ 前缀自动映射)
aiApiKey: '',
redisUrl: '',
// 客户端公开(NUXT_PUBLIC_ 前缀自动映射)
public: {
appName: '',
apiBase: '',
}
}
})映射规则:NUXT_PUBLIC_API_BASE → runtimeConfig.public.apiBase(驼峰转换)。
5.3 使用 runtimeConfig
// server/api/ai/generate.post.ts — 服务端使用私有配置
export default defineEventHandler(async (event) => {
const config = useRuntimeConfig()
// ✅ 服务端可以访问私有配置
const response = await $fetch('https://api.ai-video.com/generate', {
headers: { 'Authorization': `Bearer ${config.aiApiKey}` }
})
return response
})
// app/pages/index.vue — 客户端使用公开配置
// <script setup lang="ts">
// const config = useRuntimeConfig()
// console.log(config.public.appName) // ✅ 客户端可以访问 public 配置
// console.log(config.aiApiKey) // ❌ 客户端无法访问私有配置
// </script>5.4 .nuxtrc — 全局 Nuxt 配置
.nuxtrc 使用 flat syntax,适合设置本地开发偏好:
# .nuxtrc(全局,放在 ~ 目录下)
devtools.enabled=true
typescript.strict=true5.5 敏感变量安全实践
# .gitignore — 确保敏感文件不入库
.env.local
.env.*.local对于 CI/CD 环境,使用 GitHub Secrets 或部署平台的环境变量管理:
# .github/workflows/deploy.yml
env:
NUXT_AI_API_KEY: ${{ secrets.AI_API_KEY }}
NUXT_REDIS_URL: ${{ secrets.REDIS_URL }}6. Git 与协作规范初始化
6.1 .gitignore Nuxt 专用模板
# .gitignore
# Nuxt
.nuxt/
.output/
.data/
.nitro/
.cache/
# 依赖
node_modules/
# 环境变量
.env.local
.env.*.local
# IDE
.vscode/*
!.vscode/extensions.json
!.vscode/settings.json
!.vscode/*.code-snippets
# 系统文件
.DS_Store
Thumbs.db
# 日志
*.log6.2 Conventional Commits 规范
安装 commitlint:
pnpm add -D -w @commitlint/config-conventional @commitlint/cli// commitlint.config.js
export default {
extends: ['@commitlint/config-conventional'],
rules: {
'type-enum': [2, 'always', [
'feat', // 新功能
'fix', // 修复
'docs', // 文档
'style', // 格式
'refactor', // 重构
'perf', // 性能
'test', // 测试
'build', // 构建
'ci', // CI/CD
'chore', // 杂务
'revert', // 回退
]],
'scope-enum': [2, 'always', [
'web', // 用户前台
'admin', // 管理后台
'shared', // 共享包
'config', // 配置
'deps', // 依赖
]],
}
}提交格式示例:
git commit -m "feat(web): 添加视频列表页"
git commit -m "fix(shared): 修复类型导出错误"
git commit -m "perf(web): 优化视频列表懒加载"6.3 Husky + lint-staged 预提交钩子
# 安装
pnpm add -D -w husky lint-staged
# 初始化 Husky
pnpm exec husky init# .husky/commit-msg
npx --no -- commitlint --edit $1# .husky/pre-commit
npx lint-staged// package.json(根目录)
{
"lint-staged": {
"*.{ts,vue}": ["eslint --fix"],
"*.{json,md,yml}": ["prettier --write"]
}
}6.4 EditorConfig 跨编辑器统一
# .editorconfig
root = true
[*]
charset = utf-8
end_of_line = lf
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false本章小结
本章完成了 AI 视频项目的完整工程基座搭建:
- 运行时环境:Node.js 22 LTS + fnm + pnpm + Corepack
- 项目创建:
nuxi init+ 初始结构说明 + 常用命令速查 - Monorepo 架构:pnpm workspace + workspace 协议 + Turborepo 加速
- IDE 配置:VSCode/Cursor 插件 + settings + 代码片段
- 环境变量:分层管理 +
NUXT_前缀映射 + 安全实践 - Git 规范:Conventional Commits + Husky + lint-staged + EditorConfig
下一章,我们将深入解析 Nuxt4 的目录结构,理解每个目录的职责边界与自动化机制。