1. Nuxt 3项目环境准备与初始化
最近在帮朋友搭建一个电商网站时,我选择了Nuxt 3作为前端框架。不得不说,相比Nuxt 2,Nuxt 3在开发体验和性能上都有显著提升。但刚开始配置环境时,我也踩了不少坑,这里分享下我的经验。
首先,Node.js版本是个大问题。Nuxt 3要求Node.js版本≥18.0.0,而我的开发机默认安装的是16.x版本。升级Node.js时,我推荐使用nvm(Node Version Manager)来管理多版本:
nvm install 18 nvm use 18安装完Node.js后,创建新项目时遇到了模板下载失败的问题。这是因为GitHub的rawusercontent.com域名在国内访问不稳定。解决方法是在hosts文件中添加以下内容:
185.199.108.133 raw.githubusercontent.com 185.199.109.133 raw.githubusercontent.com 185.199.110.133 raw.githubusercontent.com 185.199.111.133 raw.githubusercontent.com保存后,执行项目初始化命令就顺利多了:
npx nuxi@latest init my-project初始化过程中会让你选择包管理器,我个人推荐pnpm,因为它比npm更快,磁盘占用更小。选择后,项目会自动安装基础依赖。完成后目录结构如下:
my-project/ ├── node_modules/ ├── nuxt.config.ts ├── package.json ├── public/ └── server/2. 项目结构与关键配置解析
Nuxt 3的目录结构相比Nuxt 2有了很大变化,更简洁但也更灵活。默认只有public和server目录,其他常用目录需要手动创建:
mkdir -p components assets pagespages目录特别重要,它用于存放页面组件,Nuxt 3会根据这个目录结构自动生成路由。比如创建pages/index.vue后,访问根路径/就会自动渲染这个组件。
app.vue是应用的根组件,默认内容很简单:
<template> <NuxtPage /> </template>NuxtPage组件相当于Vue Router的router-view,用于显示当前路由对应的页面。我通常会在这里添加一些全局布局元素,比如导航栏:
<template> <div> <AppHeader /> <NuxtPage /> <AppFooter /> </div> </template>nuxt.config.ts是项目的核心配置文件。我常用的配置项包括:
export default defineNuxtConfig({ devtools: { enabled: true }, modules: ['@nuxtjs/tailwindcss'], runtimeConfig: { public: { apiBase: process.env.API_BASE || '/api' } } })这个配置启用了开发工具,添加了Tailwind CSS模块,并设置了运行时环境变量。
3. 开发与构建优化技巧
开发过程中,我发现Nuxt 3的HMR(热模块替换)速度非常快,这要归功于Vite。但有几个优化点值得注意:
首先是自动导入功能。Nuxt 3会自动导入components/目录下的组件,无需手动import。但有时我们需要禁用这个功能,可以在nuxt.config.ts中配置:
components: { dirs: [ '~/components', { path: '~/components/base', prefix: 'Base' } ] }这样配置后,base/目录下的组件会自动加上Base前缀,避免命名冲突。
数据获取方面,Nuxt 3提供了useFetch和useAsyncData组合式函数。我的常用模式是:
<script setup> const { data: products } = await useFetch('/api/products', { pick: ['id', 'name', 'price'], transform: (data) => data.items }) </script>构建优化也很重要。生产环境构建时,我通常会添加以下配置:
nitro: { preset: 'node-server', compressPublicAssets: true, prerender: { crawlLinks: true, routes: ['/sitemap.xml'] } }这样会启用压缩、预渲染和链接爬取,显著提升SEO效果。
4. 生产环境部署实战
部署环节我尝试了多种方案,最终确定了一个稳定高效的流程。首先是构建:
npm run build构建完成后,.output目录包含了所有生产文件。我习惯用rsync同步到服务器:
rsync -avz --delete .output/ user@server:/var/www/my-project服务器上需要安装Node.js(≥18.0.0)。我推荐使用PM2来管理进程,首先全局安装:
npm install -g pm2然后创建ecosystem.config.js:
module.exports = { apps: [{ name: 'my-project', script: './server/index.mjs', instances: 'max', exec_mode: 'cluster', env: { NODE_ENV: 'production', PORT: 3000 } }] }启动应用:
pm2 start ecosystem.config.js为了让应用更稳定,我设置了开机自启和日志轮转:
pm2 startup pm2 save pm2 install pm2-logrotate5. Nginx反向代理配置
虽然Node.js可以直接对外服务,但用Nginx做反向代理更安全高效。我的典型配置如下:
server { listen 80; server_name example.com; location / { proxy_pass http://localhost:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ { expires 1y; add_header Cache-Control "public, immutable"; try_files $uri =404; } }这个配置实现了:
- 请求转发到Node.js应用
- WebSocket支持
- 静态资源长期缓存
- 真实IP传递
配置完成后,重载Nginx:
sudo nginx -s reload6. 监控与维护
线上运行后,监控很重要。PM2自带的监控命令很实用:
pm2 monit # 实时监控 pm2 logs # 查看日志我还配置了健康检查端点:
// server/api/healthz.get.ts export default defineEventHandler(() => { return { status: 'ok', timestamp: new Date() } })这样可以用curl定期检查:
curl -I http://localhost:3000/api/healthz对于性能问题,我常用的诊断步骤是:
- 用pm2 logs查看错误日志
- 用curl测试接口响应时间
- 用Chrome DevTools分析前端性能
- 必要时启用Nginx访问日志
7. 常见问题解决方案
在实际部署中,我遇到过几个典型问题:
端口冲突:如果3000端口被占用,可以在.env文件中修改:
PORT=4000内存泄漏:Node.js应用有时会出现内存增长,可以配置PM2自动重启:
// ecosystem.config.js max_memory_restart: '1G'静态资源404:确保nuxt.config.ts中配置了正确的静态资源路径:
app: { baseURL: '/', buildAssetsDir: '/_nuxt/' }SEO问题:确保正确设置了meta标签,我通常使用useHead组合式函数:
<script setup> useHead({ title: '产品页面', meta: [ { name: 'description', content: '产品详情' } ] }) </script>8. 进阶部署方案
对于高流量场景,我推荐以下优化方案:
CDN集成:在nuxt.config.ts中配置CDN地址:
app: { cdnURL: 'https://cdn.example.com' }负载均衡:在多台服务器上部署,用Nginx做负载均衡:
upstream nuxt_servers { server 192.168.1.10:3000; server 192.168.1.11:3000; server 192.168.1.12:3000; }Docker化:创建Dockerfile提升部署一致性:
FROM node:18-alpine WORKDIR /app COPY .output . EXPOSE 3000 CMD ["node", "./server/index.mjs"]构建并运行:
docker build -t my-nuxt-app . docker run -d -p 3000:3000 my-nuxt-app这些方案在我的多个生产项目中验证过,能有效提升应用的可用性和性能。