Vue 2 项目 Webpack 升级到 Vite 构建工具
将 Vue 2 + Webpack 项目升级到 Vite 构建工具。当用户需要将 Vue 2 项目从 Webpack 迁移到 Vite、优化构建速度、解决 Webpack 配置问题,或处理 Vue CLI/Webpack 与 Vite 环境变量兼容时使用此技能。触发场景包括:(1) 用户提到"升级到 Vite"、...
Rank
62
Safety
84
Downloads
1.3k
Updated
Oct 10, 2026
Version
1.0.1
Source
CLAWHUB
About
What it does, and when to use it.
Capability contract not published. No trust telemetry is available yet. 1.3K downloads reported by the source. Last updated 10/10/2026.
Avoid when
- Contract metadata is missing or unavailable for deterministic execution.
Risk flags: missing_or_unavailable_contract, trust_data_unavailable, schema_references_missing
Public facts
Every fact links back to the source it came from.
- Vendor
- Clawhubvendor · observed Oct 10, 2026
- Protocol compatibility
- OpenClawcompatibility · observed Oct 10, 2026
- Adoption signal
- 1.3K downloadsadoption · observed Oct 10, 2026
- Latest release
- 1.0.1release · observed May 18, 2026
- Handshake status
- UNKNOWNsecurity
Install and run
Setup complexity: low.
clawhub skill install s176a2rfmghg3asnngmysp6vyx86jr9c:vue2-vite-upgrade- Install using `clawhub skill install s176a2rfmghg3asnngmysp6vyx86jr9c:vue2-vite-upgrade` in an isolated environment before connecting it to live workloads.
- No published capability contract is available yet, so validate auth and request/response behavior manually.
- Review the upstream CLAWHUB listing at https://clawhub.ai/yyyyzj/vue2-vite-upgrade before using production credentials.
Contract: missing
curl -s "https://www.xpersona.co/api/v1/agents/clawhub-yyyyzj-vue2-vite-upgrade/snapshot"
Documentation
CLAWHUB
55,372 characters of source documentation, loaded on request.
Extracted files
5 files captured from the source.
SKILL.md
--- name: vue2-vite-upgrade description: 将 Vue 2 + Webpack 项目升级到 Vite 构建工具。当用户需要将 Vue 2 项目从 Webpack 迁移到 Vite、优化构建速度、解决 Webpack 配置问题,或处理 Vue CLI/Webpack 与 Vite 环境变量兼容时使用此技能。触发场景包括:(1) 用户提到"升级到 Vite"、"迁移到 Vite"、"Webpack 转 Vite";(2) 用户抱怨 Webpack 构建慢、热更新慢;(3) 用户想要现代化 Vue 2 项目的构建工具;(4) 用户遇到 Webpack 配置复杂难以维护的问题;(5) 用户询问如何提升 Vue 2 项目的开发体验;(6) 用户提到 process.env、VUE_APP_*、import.meta.env、VITE_* 等环境变量兼容。 --- # Vue 2 项目升级到 Vite 构建工具 ## 重要提示 ⚠️ **在开始之前,必须确认用户已经备份了代码或使用了 Git 版本控制!** ### 前置安全检查 阶段 2 包含删除操作(`rm -rf` / `git rm`),执行前必须确认: 1. 当前在项目根目录(`ls package.json` 存在) 2. Git 状态干净或业务代码已提交/stash(`git status`) 3. 用户已明确确认可以执行删除 4. 删除操作优先使用 `git rm`(可通过 `git restore` 恢复),非 Git 项目才使用 `rm` ## 执行原则 1. **使用 TodoWrite 工具**:创建完整的任务列表,实时更新进度 2. **分阶段执行**:按照阶段顺序执行,每个阶段完成后标记为完成 3. **遇到问题及时沟通**:使用 AskUserQuestion 询问用户 4. **保留业务依赖**:只删除 Webpack/Babel 相关依赖 ## 执行流程概览 | 阶段 | 内容 | |------|------| | 阶段 1 | 项目分析 - 分析现有项目结构、依赖和配置 | | 阶段 2 | 文件清理与配置 - 删除 Webpack 配置,创建 Vite 配置 | | 阶段 3 | 代码迁移 - 修改代码以适配 Vite | | 阶段 4 | 测试与验证 - 安装依赖并测试运行 | | 阶段 5 | 部署配置(可选)- 配置自动化部署脚本 | ## 参考文档 - **Vite 配置模板**:见 [references/vite-config.md](references/vite-config.md) - **常见问题处理**:见 [references/common-issues.md](references/common-issues.md) - **部署配置**:见 [references/deploy-config.md](references/deploy-config.md) --- ## 阶段 1:项目分析 使用 TodoWrite 创建任务列表,然后依次执行: 1. 分析 package.json(识别业务依赖、Webpack 依赖、需升级依赖) 2. 提取环境变量(从 config/*.env.js 转换为 .env.* 格式) 3. 检查代理配置(记录 proxyTable) 4. 检查特殊功能(SVG Sprite、JSX、动态路由) 5. 单独审计 `axios`:核对官方 release/security 公告,避免继续保留已披露漏洞版本;同时排查上传、导出、401/403 拦截和裸 `axios` 调用 详细步骤见 [references/migration-steps.md](references/migration-steps.md) --- ## 阶段 2:文件清理与配置 1. 删除 Webpack 相关文件(build/、config/、.babelrc 等) 2. 更新 package.json(添加 type: module,替换 scripts,更新依赖) 3. 创建 vite.config.js(使用 [references/vite-config.md](references/vite-config.md) 模板) 4. 创建环境变量文件(.env.development、.env.staging、.env.production) 详细步骤见 [references/migration-steps.md](references/migration-steps.md) --- ## 阶段 3:代码迁移 1. 修改 index.html(移动到根目录,添加 `<script type="module">`) 2. 修改 main.js(使用 render 函数,导入加 .vue 扩展名) 3. 迁移环境变量:优先使用 import.meta.env;如项目存在并行上线或老分支合并,需要保留 process.env.VUE_APP_* 静态写法兼容层 4. 处理静态资源(static → public,~@ → @,global → window) 5. 修改组件导入(所有 .vue 导入加扩展名) 6. 修复样式(/deep/ 和 >>> → ::v-deep) 详细步骤见 [references/migration-steps.md](references/migration-steps.md) --- ## 环境变量兼容约定 迁移期如果可能有 Webpack/Vue CLI 写法的需求先合入生产,不要只做 `process.env -> import.meta.env` 的单向替换。 1. `.env.*` 中新增变量优先使用 `VITE_` 前缀。 2. Vite 代码推荐使用 `import.meta.env.VITE_*`。 3. Webpack/Vue CLI 历史代码允许继续使用 `process.env.VUE_APP_*`。 4. 在 `vite.config.js` 中用 `loadEnv(mode, process.cwd(), '')` 读取变量,并自动把 `VITE_XXX` 映射为 `process.env.VUE_APP_XXX`。 5. 如果 `.env.*` 已存在 `VUE_APP_XXX`,也要原样注入为 `process.env.VUE_APP_XXX`。 6. `define` 使用精确 key,不整体替换 `process.env`,减少对第三方库和动态访问的影响。 7. 兼容层只保证静态写法,如 `process.env.VUE_APP_BASE_API`;不承诺兼容 `process.env[key]`。 具体配置示例见 [references/vite-config.md](references/vite-config.md)。 --- ## 阶段 4:测试与验证 1. 安装依赖:先执行 `pnpm install`;如
_meta.json
{
"ownerId": "kn7ff3q7khffkrpd622drjz91n86k0sv",
"slug": "vue2-vite-upgrade",
"version": "1.0.1",
"publishedAt": 1779072590618
}references/common-issues.md
# 常见问题处理
在升级过程中如果遇到以下错误,按照对应方案处理。
## 目录
- [问题 1:require is not defined](#问题-1require-is-not-defined)
- [问题 2:找不到模块](#问题-2找不到模块cannot-find-module)
- [问题 3:process is not defined](#问题-3process-is-not-defined)
- [问题 4:global is not defined](#问题-4global-is-not-defined)
- [问题 5:图片 require 报错](#问题-5图片-require-报错)
- [问题 6:环境变量判断不生效](#问题-6环境变量判断不生效)
- [问题 7:SCSS :export 不工作](#问题-7scss-export-导出变量不工作)
- [问题 8:JSX 报错](#问题-8vue-文件中使用-jsx-报错)
- [问题 9:HTMLCollection 没有 forEach](#问题-9htmlcollection-没有-foreach-方法)
- [问题 10:导航守卫重定向报错](#问题-10vue-router-导航守卫重定向报错)
- [问题 11:Element-UI 样式丢失](#问题-11element-ui-样式丢失)
- [问题 12:SVG Sprite 图标不显示](#问题-12svg-sprite-图标不显示)
- [问题 13:热更新不生效](#问题-13热更新-hmr-不生效)
- [问题 14:生产构建路径错误](#问题-14生产构建后路径错误)
- [问题 15:path 模块不可用](#问题-15nodejs-path-模块在浏览器不可用)
- [问题 16:axios 安全漏洞](#问题-16axios-版本存在安全漏洞)
- [问题 17:浏览器兼容性](#问题-17浏览器兼容性问题需要支持旧浏览器)
- [问题 18:router.app.$store 为 undefined](#问题-18routerappstore-为-undefined)
- [问题 19:chunk 体积过大](#问题-19构建后-chunk-体积过大警告)
- [问题 20:路由懒加载](#问题-20路由组件未实现懒加载导致主包过大)
- [问题 21:静态资源 404](#问题-21静态资源-404-错误publicdir-配置)
- [问题 22:正则匹配 null](#问题-22正则匹配结果为-null-导致运行时报错)
- [问题 23:动态导入冲突](#问题-23动态导入与静态导入冲突警告)
---
## 问题 1:require is not defined
**原因:** Vite 不支持 CommonJS 的 require 语法
**解决方案:**
1. 将 CommonJS 依赖加入 `vite.config.js` 的 `optimizeDeps.include`
2. 如果是代码中使用了 require,改为 import 语法
---
## 问题 2:找不到模块(Cannot find module)
**原因:** 导入路径缺少 `.vue` 扩展名,或 Vite 默认不自动补全扩展名
**解决方案:**
**方案一:配置 `resolve.extensions`(推荐,批量解决)**
在 `vite.config.js` 中添加:
```javascript
resolve: {
extensions: ['.js', '.vue', '.json', '.ts'],
alias: { /* ... */ }
}
```
> 注意:Vite 官方不推荐省略 `.vue` 扩展名,配置此项后仍建议逐步补全扩展名。
**方案二:手动补全扩展名**
```bash
# 搜索所有缺少 .vue 扩展名的导入
grep -rn "from ['\"].*@/.*['\"]" src --include="*.js" --include="*.vue" | grep -v "\.vue"
```
---
## 问题 3:process is not defined
**原因:** 第三方库使用了 Node.js 的 process 对象
**解决方案:** 在 `vite.config.js` 中添加:
```javascript
export default defineConfig({
define: {
'process.env': {},
'process.platform': JSON.stringify(''),
'process.version': JSON.stringify('')
}
})
```
---
## 问题 4:global is not defined
**原因:** 代码中使用了 Node.js 的 global 对象
**解决方案:** 全局替换 `global.` 为 `window.`
```bash
find src -type f \( -name "*.js" -o -name "*.vue" \) -exec sed -i '' 's/global\./window./g' {} +
```
---
## 问题 5:图片 require 报错
**原因:** Vite 不支持 require 动态导入图片
**解决方案:**
```javascript
// ❌ 错误
<img :src="require('@/assets/logo.png')" />
// ✅ 方案一:使用 import
import logo from '@/assets/logo.png'
// template 中使用 :src="logo"
// ✅ 方案二:public 目录下的资源直接用绝对路径
<img src="/images/logo.png" />
```
---
## 问题 6:环境变量判断不生效
**原因:** Vite 使用 `import.meta.env` 而非 `process.env`,且只暴露 `VITE_` 前缀变量
**解决方案:**
**情况一:新代码用了 Vite 内置 MODE 变量但不匹配**
```javascript
// ❌ 错误
import.meta.env.MODE === 'testing' // 永远不匹配
// ✅ 正确:使用自定义的 VITE_RUN_ENV 变量
import.meta.env.VITE_RUN_ENV === 'staging'
```
**情况二:老代码使用 `process.env.VUE_APP_*`,通过配置兼容**
在 `vite.config.js` 中用 `define` 静态替换,无需修改业务代码:
```javascript
import { definreferences/deploy-config.md
# 部署配置
## NPM 脚本
```json
"scripts": {
"dev": "vite",
"start": "pnpm run dev",
"build": "vite build",
"preview": "vite preview",
"build:stage": "pnpm run build --mode staging",
"build:prod": "pnpm run build --mode production",
"clean": "rimraf dist.zip",
"zip": "node export-zip.cjs",
"upload:stage": "node ftp-deploy.js stage",
"upload:prod": "node ftp-deploy.js production",
"deploy:stage": "pnpm run build:stage && pnpm run clean && pnpm run zip && pnpm run upload:stage",
"deploy:prod": "pnpm run build:prod && pnpm run clean && pnpm run zip && pnpm run upload:prod"
}
```
---
## 压缩脚本 (export-zip.cjs)
```javascript
const fs = require('fs');
const archiver = require('archiver');
const homedir = __dirname;
const target = ['dist'];
const output = fs.createWriteStream(homedir + '/dist.zip');
const archive = archiver('zip', { zlib: { level: 9 } });
archive.on('error', function (err) { throw err; });
output.on('close', function () {
console.log(`压缩完毕,大小: ${(archive.pointer() / 1024 / 1024).toFixed(1)} MB`);
});
archive.pipe(output);
for (let i of target) {
archive.directory(i, i);
}
archive.finalize();
```
---
## FTP 部署脚本 (ftp-deploy.js)
> ⚠️ **安全提示**:部署凭证**不要**硬编码在脚本中或使用 Git 提交。通过环境变量或 `.env` 文件(已加入 `.gitignore`)传入。生产环境部署只在显式确认后执行。
```javascript
import FtpDeploy from "ftp-deploy";
import { fileURLToPath } from "node:url";
import path from "node:path";
const ftpDeploy = new FtpDeploy();
const env = process.argv.splice(2)[0];
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// 从环境变量读取部署凭证,未设置时报错
function getEnvConfig(targetEnv) {
const prefix = targetEnv === 'production' ? 'PROD' : 'STAGE';
const user = process.env[`${prefix}_FTP_USER`];
const password = process.env[`${prefix}_FTP_PASSWORD`];
const host = process.env[`${prefix}_FTP_HOST`];
const remoteRoot = process.env[`${prefix}_FTP_REMOTE_ROOT`];
if (!user || !password || !host || !remoteRoot) {
console.error(`\x1b[31mError: Missing ${prefix}_FTP_* environment variables\x1b[0m`);
process.exit(1);
}
return { user, password, host, remoteRoot };
}
if (!env || !['stage', 'production'].includes(env)) {
console.error('\x1b[31m%s\x1b[0m', 'error: 环境参数错误,请使用 stage 或 production');
process.exit(1);
}
const envConfig = getEnvConfig(env);
const config = {
...envConfig,
port: 21,
localRoot: __dirname + "/",
include: ["dist.zip"],
deleteRemote: false,
forcePasv: true,
sftp: false,
};
ftpDeploy.deploy(config)
.then(() => console.log('upload completed'))
.catch((err) => console.log(err));
```
**使用方式:**
```bash
# 临时设置(单次部署)
STAGE_FTP_USER=myuser STAGE_FTP_PASSWORD=mypass STAGE_FTP_HOST=ftp.example.com STAGE_FTP_REMOTE_ROOT=/staging/ pnpm run upload:stage
# 或通过 .env.local 文件(需已加入 .gitignore)
# 在 .env.local 中写入:
# STAGE_FTP_USER=myuser
# STAGE_FTP_PASSWORD=mypass
# STAGE_FTP_HOST=ftp.example.com
# STAGE_FTP_REMOTE_ROOT=/stagireferences/migration-steps.md
# 迁移步骤详解
## 目录
- [1. 分析 package.json](#1-分析-packagejson)
- [2. 提取环境变量](#2-提取环境变量)
- [3. 删除 Webpack 文件](#3-删除-webpack-文件)
- [4. 更新 package.json](#4-更新-packagejson)
- [5. 创建环境变量文件](#5-创建环境变量文件)
- [6. 修改 index.html](#6-修改-indexhtml)
- [7. 修改 main.js](#7-修改-mainjs)
- [8. 全局替换环境变量](#8-全局替换环境变量)
- [9. 处理静态资源](#9-处理静态资源)
- [10. 修改组件导入](#10-修改组件导入)
- [11. 修复样式问题](#11-修复样式问题)
---
## 1. 分析 package.json
读取 package.json,识别依赖类型:
**保留的业务依赖:** axios, element-ui, lodash, qs, echarts, moment 等
**需要删除的 devDependencies:**
- webpack, webpack-*, babel-*
- html-webpack-plugin, extract-text-webpack-plugin
- css-loader, style-loader, sass-loader, vue-loader
- node-sass(替换为 sass)
- vue-template-compiler(Vue 2.7 不需要)
**需要升级的核心依赖:**
- vue → ^2.7.16
- vue-router → ^3.6.5
- vuex → ^3.6.2
- element-ui → ^2.15.14
- axios → 当前 1.x 安全补丁版本(执行迁移当天先核对官方 release/security,不再在 skill 中固定写死具体补丁号)
**axios 迁移检查:**
- 如果项目还在 `0.x` 或早期 `1.x`,先升级到当前 1.x 安全补丁版本,再继续做 Vite 迁移
- 搜索是否存在 `CancelToken`、`axios.all`、`axios.spread`、`headers.post['Content-Type']`
- 搜索是否存在裸 `import axios from 'axios'`;如果这些请求也需要统一 token、401/403、加解密逻辑,应迁回统一 request 封装
- 对 `FormData` 上传优先直接传 `FormData`,不要继续依赖 `delete headers.post['Content-Type']` 这类旧写法
- 重点回归上传、文件导出、401/403 跳转、刷新 token 这几类接口
---
## 2. 提取环境变量
读取 config/dev.env.js、config/prod.env.js 等文件,转换格式:
```javascript
// Webpack 格式
module.exports = { BASE_API: '"https://api.example.com"' }
// Vite 格式 (.env.development)
VITE_BASE_API=https://api.example.com
```
---
## 3. 删除 Webpack 文件
> ⚠️ **执行前确认**:以下命令会永久删除文件。确保已在正确的项目根目录执行,且代码已提交或备份。
**3.1 前置安全检查**
```bash
# 确认在项目根目录
pwd
# 确认 Git 状态干净(无未提交的破坏性变更)
git status --short
# 如果存在未提交的业务代码,先提交或 stash
git stash push -m "before vite migration"
```
**3.2 使用 Git 删除(可撤销)**
优先使用 `git rm` 而非 `rm`,以便通过 `git restore` 恢复:
```bash
# 删除 Webpack 构建目录
git rm -rf build/ config/
# 删除 Babel/PostCSS 配置
git rm -f .babelrc .postcssrc.js babel.config.js
# 删除旧锁文件(pnpm 项目不需要 npm/yarn 锁文件)
git rm -f package-lock.json yarn.lock 2>/dev/null || true
```
如果项目未纳入 Git 版本控制,使用以下命令(**不可撤销,执行前务必确认**):
```bash
rm -rf build/ config/
rm -f .babelrc .postcssrc.js babel.config.js
rm -f package-lock.json yarn.lock
```
**3.3 删除后验证**
```bash
# 确认目标目录已不存在
ls build config .babelrc .postcssrc.js babel.config.js 2>&1 | grep -q "No such" && echo "清理完成" || echo "警告:部分文件仍存在"
```
---
## 4. 更新 package.json
**关键修改:**
1. 添加 `"type": "module"`
2. 替换 scripts:
```json
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview",
"build:stage": "pnpm run build --mode staging",
"build:prod": "pnpm run build --mode production"
}
```
3. 新的 devDependencies:
```json
"devDependencies": {
"@vitejs/plugin-vue2": "^2.3.1",
"sass": "^1.77.0",
"vite": "^4.5.5",
"vite-plugin-compression": "^0.5.1"
}
```
4. 如果使用 JSX,添加:`"@vitejs/plugin-vue2-jsx": "^2.1.1"`
5. 如果使用 SVG Sprite,添加:`"vite-plugin-svg-icons": "^2.0.1"`
---
## 5. 创建环境变量文件
创建 .env.development、.env.staging、.env.production:
```bash
VITE_RUN_ENV=development
VITE_BASE_AionUi
Free, local, open-source 24/7 Cowork app and OpenClaw for Gemini CLI, Claude Code, Codex, OpenCode, Qwen Code, Goose CLI, Auggie, and more | 🌟 Star if you like it!
activepieces
AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents
cherry-studio
AI productivity studio with smart chat, autonomous agents, and 300+ assistants.
CopilotKit
The Frontend for Agents & Generative UI. React + Angular
Machine-readable data
The same record, as JSON, for agents and crawlers.
{
"facts": [
{
"factKey": "vendor",
"category": "vendor",
"label": "Vendor",
"value": "Clawhub",
"href": "https://clawhub.ai/yyyyzj/skills/vue2-vite-upgrade",
"sourceUrl": "https://clawhub.ai/yyyyzj/skills/vue2-vite-upgrade",
"sourceType": "profile",
"confidence": "medium",
"observedAt": "2026-10-10T17:57:38.468Z",
"isPublic": true
},
{
"factKey": "protocols",
"category": "compatibility",
"label": "Protocol compatibility",
"value": "OpenClaw",
"href": "https://www.xpersona.co/api/v1/agents/clawhub-yyyyzj-vue2-vite-upgrade/contract",
"sourceUrl": "https://www.xpersona.co/api/v1/agents/clawhub-yyyyzj-vue2-vite-upgrade/contract",
"sourceType": "contract",
"confidence": "medium",
"observedAt": "2026-10-10T17:57:38.468Z",
"isPublic": true
},
{
"factKey": "traction",
"category": "adoption",
"label": "Adoption signal",
"value": "1.3K downloads",
"href": "https://clawhub.ai/yyyyzj/vue2-vite-upgrade",
"sourceUrl": "https://clawhub.ai/yyyyzj/vue2-vite-upgrade",
"sourceType": "profile",
"confidence": "medium",
"observedAt": "2026-10-10T17:57:38.468Z",
"isPublic": true
},
{
"factKey": "latest_release",
"category": "release",
"label": "Latest release",
"value": "1.0.1",
"href": "https://clawhub.ai/yyyyzj/vue2-vite-upgrade",
"sourceUrl": "https://clawhub.ai/yyyyzj/vue2-vite-upgrade",
"sourceType": "release",
"confidence": "medium",
"observedAt": "2026-05-18T02:49:50.618Z",
"isPublic": true
},
{
"factKey": "handshake_status",
"category": "security",
"label": "Handshake status",
"value": "UNKNOWN",
"href": "https://www.xpersona.co/api/v1/agents/clawhub-yyyyzj-vue2-vite-upgrade/trust",
"sourceUrl": "https://www.xpersona.co/api/v1/agents/clawhub-yyyyzj-vue2-vite-upgrade/trust",
"sourceType": "trust",
"confidence": "medium",
"observedAt": null,
"isPublic": true
}
],
"events": [
{
"eventType": "release",
"title": "Release 1.0.1",
"description": "Version 1.0.1 - 新增阶段 2 删除操作前的安全检查,包括要求在项目根目录、Git 状态干净并获得用户确认,优先使用 git rm。 - 阶段 4 安装依赖步骤细化,要求优先手动排查 peer dependency 冲突,再考虑使用 --force,并关注 lockfile 变更。 - 部署脚本安全更新:禁止在部署脚本中硬编码凭证,必须通过环境变量传递,并在生产部署前需显式确认。 - 文档表述更明确,强调数据安全流程,优化升级操作规范。",
"href": "https://clawhub.ai/yyyyzj/vue2-vite-upgrade",
"sourceUrl": "https://clawhub.ai/yyyyzj/vue2-vite-upgrade",
"sourceType": "release",
"confidence": "medium",
"observedAt": "2026-05-18T02:49:50.618Z",
"isPublic": true
}
]
}Record generated Oct 10, 2026.
