使用 Vite 构建 Vue 项目的流程非常简洁

  1. 创建项目:npm create vite@latest
  2. 安装依赖:cd my-project && npm install
  3. 开发调试:npm run dev
  4. 生产环境构建部署:npm run build;测试环境构建部署:npm run build:test
  5. 预览生产版本:npm run preview
1
2
3
4
5
6
7
# package.json
"scripts": {
    "dev": "vite",
    "build": "vue-tsc -b && vite build",
    "build:test": "vue-tsc -b && vite build --mode development",
    "preview": "vite preview"
},

环境文件

Vite 根据运行的命令自动选择对应的环境文件:

命令 mode 加载的文件(按优先级从高到低)
npm run dev development .env.development.env
npm run build:test development .env.development.env
npm run preview production .env.production.env
npm run build production .env.production.env

Vite 创建的 Vue 项目结构

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
my-vue-app/
├── node_modules/        # 项目依赖,由 npm install 生成
├── public/              # 静态资源目录。这里的文件会被直接复制到最终构建的根目录,不会被编译。
│   └── favicon.ico
├── src/                 # 源代码目录,你的主要工作区域
│   ├── assets/          # 存放需要被 Vite 处理的静态资源,如图片、CSS 等。
│   ├── components/      # 存放可复用的 Vue 组件。
│   │   └── HelloWorld.vue
│   ├── router/          # 路由配置文件 (如果选择了路由)。
│   ├── stores/          # Pinia 状态管理文件 (如果选择了 Pinia)。
│   ├── views/           # 存放页面级别的组件。
│   ├── App.vue          # 根组件。
│   ├── main.ts          # 入口文件。应用从这里开始执行。
│   └── style.css        # 全局样式文件。
├── .eslintrc.js         # ESLint 配置文件,用于代码检查。
├── .gitignore           # Git 忽略文件配置。
├── index.html           # 应用的 HTML 入口文件。
├── package.json         # 项目配置文件,包含依赖、脚本命令等。
├── tsconfig.json        # TypeScript 配置文件。
└── vite.config.ts       # Vite 的核心配置文件。

部署到生产环境

步骤一:构建生产版本

1
2
3
4
5
6
7
cd /Users/xxx/dnmp/www/xxx-front

# 1. 安装依赖(如果没安装)
npm install

# 2. 构建生产版本
npm run build

构建完成后会生成 dist 目录,里面就是可部署的静态文件。

步骤二:Nginx 部署

  1. dist 目录上传到服务器
  2. 配置 Nginx:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
server {
    listen 80;
    server_name your-domain-xxxx.com;
    root /path/to/dist;
    index index.html;

    # 处理 Vue Router 的 history 模式
    location / {
        try_files $uri $uri/ /index.html;
    }

    # API 代理到后端
    location /tg {
        proxy_pass https://api.xxx.com;
        proxy_set_header Host $host;
        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|woff|woff2)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
}