简介:从环境准备到生产环境部署,本文通过分步教学与实操案例,系统讲解Vue项目部署全流程,涵盖静态资源优化、服务器配置、自动化部署等核心环节。
部署Vue项目前需确保服务器环境满足以下条件:
node -v和npm -v验证安装在vue.config.js中配置生产环境优化:
module.exports = {publicPath: process.env.NODE_ENV === 'production' ? '/prod/' : '/',productionSourceMap: false, // 关闭source map防止源码泄露configureWebpack: {optimization: {splitChunks: {chunks: 'all' // 代码分割优化}}}}
执行npm run build生成dist目录,通过webpack-bundle-analyzer分析包体积:
npm install webpack-bundle-analyzer --save-dev# 在vue.config.js中添加const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;module.exports = {plugins: [new BundleAnalyzerPlugin()]}
文件传输:
scp命令上传dist目录:
scp -r dist username@server_ip:/path/to/project
rsync -avz --delete dist/ username@server_ip:/path/to/project
Nginx配置:
server {listen 80;server_name example.com;root /path/to/project;index index.html;location / {try_files $uri $uri/ /index.html; # 支持SPA路由}# 静态资源缓存配置location ~* \.(js|css|png|jpg)$ {expires 1y;add_header Cache-Control "public";}}
配置后执行nginx -t测试,重启服务systemctl restart nginx
安装PM2:
npm install pm2 -gpm2 startup # 生成开机自启命令
创建部署脚本deploy.sh:
#!/bin/bashgit pull origin mainnpm install --productionnpm run buildpm2 restart vue-app
配置Git仓库Webhook,指向服务器部署接口
创建Dockerfile:
FROM nginx:alpineCOPY dist /usr/share/nginx/htmlCOPY nginx.conf /etc/nginx/conf.d/default.confEXPOSE 80
构建并运行:
docker build -t vue-app .docker run -d -p 8080:80 --name vue-container vue-app
修改vue.config.js配置CDN:
module.exports = {chainWebpack: config => {config.plugin('html').tap(args => {args[0].cdn = {css: ['https://cdn.example.com/bootstrap.min.css'],js: ['https://cdn.example.com/vue.min.js','https://cdn.example.com/vue-router.min.js']}return args})}}
在public/index.html中添加CDN资源引用
使用dotenv管理不同环境变量:
.env.production、.env.staging等文件修改vue.config.js:
const dotenv = require('dotenv');const envFile = `.env.${process.env.NODE_ENV}`;dotenv.config({ path: envFile });module.exports = {publicPath: process.env.VUE_APP_PUBLIC_PATH}
Nginx需配置try_files重定向到index.html:
location / {try_files $uri $uri/ /index.html;}
开发环境配置代理:
// vue.config.jsmodule.exports = {devServer: {proxy: {'/api': {target: 'http://backend.com',changeOrigin: true}}}}
生产环境通过Nginx反向代理:
location /api {proxy_pass http://backend.com;proxy_set_header Host $host;}
集成Sentry错误监控:
在main.js中初始化:
import * as Sentry from '@sentry/vue';Sentry.init({dsn: 'YOUR_DSN',integrations: [new Sentry.Integrations.BrowserTracing()],});
使用Lighthouse进行定期审计
HTTPS配置:
sudo apt install certbot python3-certbot-nginxsudo certbot --nginx -d example.com
安全头设置:
add_header X-Content-Type-Options "nosniff";add_header X-Frame-Options "SAMEORIGIN";add_header X-XSS-Protection "1; mode=block";add_header Content-Security-Policy "default-src 'self'";
防止目录遍历:
autoindex off;
创建.github/workflows/deploy.yml:
name: Deploy Vue Appon:push:branches: [ main ]jobs:deploy:runs-on: ubuntu-lateststeps:- uses: actions/checkout@v2- uses: actions/setup-node@v2with: { node-version: '16' }- run: npm install- run: npm run build- name: Deploy to Serveruses: appleboy/ssh-action@masterwith:host: ${{ secrets.SSH_HOST }}username: ${{ secrets.SSH_USERNAME }}key: ${{ secrets.SSH_PRIVATE_KEY }}script: |cd /path/to/projectgit pull origin mainnpm install --productionpm2 restart vue-app
使用PM2的日志管理:
pm2 logs vue-app
配置自动回滚脚本:
#!/bin/bashif ! curl -sI http://localhost:8080 | grep -q "200 OK"; thenpm2 rollback vue-appfi
功能测试:
性能测试:
安全扫描:
通过本文的完整部署方案,开发者可以系统掌握Vue项目从开发到生产的全流程部署技术。实际部署时应根据项目规模选择合适方案:中小型项目推荐手动部署+Nginx配置;中大型项目建议采用Docker容器化+CI/CD自动化部署。持续监控与优化是保持应用稳定运行的关键,建议建立每周性能审计机制,及时处理发现的问题。