Appearance
第14章:部署与上线
1. 项目打包(nuxt build 命令)
基本打包:
bash
# 使用 npm
npm run build
# 使用 pnpm
pnpm build
# 使用 yarn
yarn build构建分析:
bash
# 使用 npm
npm run build -- --analyze
# 使用 pnpm
pnpm build --analyze
# 使用 yarn
yarn build --analyze构建选项:
typescript
// nuxt.config.ts
export default defineNuxtConfig({
build: {
analyze: true, // 构建分析
transpile: ['@vueuse/core'], // 需要转译的依赖
cssSourceMap: true, // 启用 CSS 源映射
extractCSS: true, // 提取 CSS 到单独的文件
optimization: {
splitChunks: {
chunks: 'all',
automaticNameDelimiter: '.',
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all'
}
}
}
}
}
})2. 部署方式详解
2.1 服务器部署(Nginx 配置、PM2 管理进程)
部署步骤:
构建项目:
bashnpm run build上传构建文件:
- 将
dist目录上传到服务器
- 将
安装依赖:
bashnpm install --production使用 PM2 管理进程:
bash# 安装 PM2 npm install -g pm2 # 启动应用 pm2 start npm --name "nuxt-app" -- run start # 查看进程状态 pm2 status # 停止应用 pm2 stop nuxt-app # 重启应用 pm2 restart nuxt-app # 查看应用日志 pm2 logs nuxt-appNginx 配置:
nginxserver { 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; } # 静态资源缓存 location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ { expires 30d; add_header Cache-Control "public, max-age=2592000"; proxy_pass http://localhost:3000; } }HTTPS 配置:
nginxserver { listen 80; server_name example.com; return 301 https://$host$request_uri; } server { listen 443 ssl http2; server_name example.com; ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; ssl_protocols TLSv1.2 TLSv1.3; ssl_prefer_server_ciphers off; 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; } }
2.2 云平台部署(Vercel、Netlify、阿里云、腾讯云)
Vercel 部署:
连接 GitHub 仓库:
- 登录 Vercel 账号
- 点击 "New Project"
- 选择你的 GitHub 仓库
配置构建选项:
- Framework Preset: Nuxt.js
- Build Command:
npm run build - Output Directory:
dist - Environment Variables: 添加必要的环境变量
部署:
- 点击 "Deploy"
- Vercel 会自动构建和部署你的应用
Netlify 部署:
连接 GitHub 仓库:
- 登录 Netlify 账号
- 点击 "Add new site"
- 选择 "Import an existing project"
- 选择你的 GitHub 仓库
配置构建选项:
- Build Command:
npm run build - Publish Directory:
dist - Environment Variables: 添加必要的环境变量
- Build Command:
部署:
- 点击 "Deploy site"
- Netlify 会自动构建和部署你的应用
阿里云部署:
创建 ECS 实例:
- 登录阿里云控制台
- 创建 ECS 实例(选择合适的配置)
配置安全组:
- 开放 80、443、3000 端口
部署应用:
- 使用 SSH 连接到 ECS 实例
- 安装 Node.js
- 克隆代码仓库
- 安装依赖并构建项目
- 使用 PM2 启动应用
- 配置 Nginx 反向代理
腾讯云部署:
创建 CVM 实例:
- 登录腾讯云控制台
- 创建 CVM 实例(选择合适的配置)
配置安全组:
- 开放 80、443、3000 端口
部署应用:
- 使用 SSH 连接到 CVM 实例
- 安装 Node.js
- 克隆代码仓库
- 安装依赖并构建项目
- 使用 PM2 启动应用
- 配置 Nginx 反向代理
2.3 容器化部署(Docker 配置,简单了解)
创建 Dockerfile:
dockerfile
# 基础镜像
FROM node:18-alpine
# 设置工作目录
WORKDIR /app
# 复制 package.json 和 package-lock.json
COPY package*.json ./
# 安装依赖
RUN npm install
# 复制源代码
COPY . .
# 构建项目
RUN npm run build
# 暴露端口
EXPOSE 3000
# 启动应用
CMD ["npm", "run", "start"]创建 .dockerignore 文件:
node_modules
.nuxt
dist
.env
.git
.gitignore
Dockerfile
.dockerignore构建和运行 Docker 容器:
bash
# 构建镜像
docker build -t nuxt-app .
# 运行容器
docker run -p 3000:3000 --name nuxt-app nuxt-app
# 后台运行容器
docker run -d -p 3000:3000 --name nuxt-app nuxt-app
# 查看容器状态
docker ps
# 查看容器日志
docker logs nuxt-app
# 停止容器
docker stop nuxt-app
# 删除容器
docker rm nuxt-app使用 Docker Compose:
yaml
# docker-compose.yml
version: '3'
services:
nuxt-app:
build: .
ports:
- "3000:3000"
environment:
- NODE_ENV=production
restart: alwaysbash
# 启动服务
docker-compose up -d
# 停止服务
docker-compose down
# 查看服务状态
docker-compose ps3. 部署常见问题排查(端口占用、跨域、静态资源访问失败)
3.1 端口占用
问题:启动应用时提示端口被占用
解决方案:
查看端口占用:
bash# Linux/macOS lsof -i :3000 # Windows netstat -ano | findstr :3000终止占用端口的进程:
bash# Linux/macOS kill -9 <PID> # Windows taskkill /PID <PID> /F修改应用端口:
typescript// nuxt.config.ts export default defineNuxtConfig({ server: { port: 3001 // 修改端口 } })
3.2 跨域问题
问题:API 请求出现跨域错误
解决方案:
使用代理:
typescript// nuxt.config.ts export default defineNuxtConfig({ modules: ['@nuxtjs/axios'], axios: { proxy: true }, proxy: { '/api': { target: 'https://api.example.com', pathRewrite: { '^/api': '' } } } })服务器端设置 CORS:
typescript// server/middleware/cors.ts
export default defineEventHandler((event) => { event.node.res.setHeader('Access-Control-Allow-Origin', '*') event.node.res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS') event.node.res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization')
if (event.node.req.method === 'OPTIONS') { event.node.res.statusCode = 204 return } })
### 3.3 静态资源访问失败
**问题**:静态资源(图片、CSS、JS)无法访问
**解决方案**:
1. **检查静态资源路径**:
- 确保静态资源放在 `public` 目录下
- 使用正确的路径引用静态资源
2. **配置 Nginx 静态资源访问**:
```nginx
location /_nuxt/ {
alias /path/to/nuxt-app/.nuxt/dist/client/;
expires 30d;
add_header Cache-Control "public, max-age=2592000";
}
location / {
proxy_pass http://localhost:3000;
}- 检查构建配置:typescript
// nuxt.config.ts export default defineNuxtConfig({ app: { baseURL: '/', // 确保基础路径正确 } })
3.4 其他常见问题
500 错误:
- 检查服务器日志
- 检查环境变量配置
- 检查 API 连接
404 错误:
- 检查路由配置
- 检查页面文件是否存在
- 检查 Nginx 配置
内存不足:
- 增加服务器内存
- 优化应用内存使用
- 配置 PM2 内存限制
小结
本章介绍了 Nuxt.js 应用的部署与上线,包括项目打包、部署方式详解以及部署常见问题排查等内容。通过本章的学习,你应该已经掌握了如何将 Nuxt.js 应用部署到不同的环境,以及如何排查和解决部署过程中遇到的常见问题。
在接下来的章节中,我们将学习 Nuxt.js 的常见问题与面试题,帮助你进一步提升 Nuxt.js 开发技能和准备面试。
