老项目vue2+webpack改用vite避坑指南

项目痛点

npm run dev
DONE  Compiled successfully in 698066ms

好家伙启动一次项目十多分钟,而且还是多项目开发,本地项目启多了电脑还卡,如果遇到一个线上紧急问题,等项目启动完估计直接回家种地了,这玩意谁能受得了。

据说vite可以提升项目启动速度,那就试试呗~

 

版本问题

vue版本为v2.7.14,vue2.7支持vue3的一些特性。

vuetitfy v2.7

推荐使用Vite 4.x版本‌,它是最后一个官方支持Vue 2的主版本,可与@vitejs/plugin-vue2插件配合使用

Vite requires Node.js version 14.18+, 16+.

 

安装依赖

npm install vite@4.5.3 @vitejs/plugin-vue2 --save-dev
pnpm add -D vite@4.5.3 @vitejs/plugin-vue2
pnpm add -D vite-plugin-vue2

 

创建vite.config.js


 import { defineConfig } from 'vite'
 import vue from '@vitejs/plugin-vue2'
 import path from 'node:path'
 import packageJson from './package.json'
// 保持与原有项目一致的版本变量
process.env.VUE_APP_VERSION = packageJson.version;
const TIMEOUT = 6 * 60 * 1000;

// Vite 配置:将原有的 webpack 配置替换为 Vite
module.exports = defineConfig(({ command }) => ({
    plugins: [vue()], 
    resolve: {
        alias: {
             '@': path.resolve(__dirname, 'src'),
        },
      extensions: ['.js', '.vue', '.json'], // 自动补全扩展名
    },
  server: {
    port: 8080, // 保持与 Webpack devServer 一致
    proxy: {
      // API 代理配置
      '/api': {
        target: 'http://localhost:3000',
        changeOrigin: true
      }
    }
  },
  build: {
    outDir: 'dist', // 输出目录
    assetsDir: 'static',
    // 代码分割配置
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ['vue', 'vue-router', 'vuex'],
          // 其他第三方库
        }
      }
    },
    // 生产环境去除 console 和 debugger
    minify: 'terser',
    terserOptions: {
      compress: {
        drop_console: true,
        drop_debugger: true
      }
    }
  }
})

 

改造package.json

 

// 在 webpack 项目中 
  "scripts": {
      "dev": "vue-cli-service serve --mode dev",
      "build:dev": "vue-cli-service build --mode dev",
      "build:prod": "vue-cli-service build --mode prod",
  },
// 在 vite 项目中
"scripts": {
    "dev": "vite","build": "vite build --mode development","build:prod": "vite build --mode production",
},

 

创建index.html文件

Vite 需要根目录的 index.html 作为入口。关键:<script type="module"> 指向你的入口文件。

<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JCS(vue2 vite)</title>
</head>

<body>
    <div id="app"></div>
    <script type="module" src="/src/main.js"></script>
</body>

</html>

 

运行项目

pnpm dev

 

代码兼容性改造

1、环境变量迁移

项目报错:Uncaught ReferenceError: process is not defined

Vite 使用 import.meta.env 替代 process.env。【注意:环境变量必须以 VITE_ 开头才能暴露到客户端。】

// 旧代码
process.env.VUE_APP_API_URL
// 新代码
import.meta.env.VITE_API_URL

如果不想全局替换,可使用插件兼容:

pnpm add -D vite-plugin-env-compatible

vite.config.js 中配置:

import EnvCompatible from 'vite-plugin-env-compatible';

export default defineConfig({
  plugins: [
    vue(),
    EnvCompatible(),
  ]
})

2、require.context 是 Webpack 的专属 API,Vite 完全不支持;Vite 中对应的替代方案是 import.meta.glob

项目报错:Uncaught ReferenceError: require is not defined
// 修改前
importAll(require.context('./components/', true, /\.vue$/), (component) => { Vue.component(component.default.name, component.default || component); }); // 修改后 const components = import.meta.glob('./components/**/*.vue', { eager: true }) Object.entries(components).forEach(([filePath, module]) => { const component = module.default if (component && component.name) { Vue.component(component.name, component) } })

3、Vite 严格遵循原生 ESM 规范,不会像 Webpack 那样自动把 CommonJS 的 module.exports 映射为 ESM 的默认导出,因此直接触发 “找不到 default 导出” 的语法错误。

// 修改前
import accounting from 'accounting-js';
// 修改后
import * as accounting from 'accounting-js';

4、Uncaught ReferenceError: global is not defined

global 是 Node.js 专属的全局对象,浏览器环境中对应的全局对象是 window,而非 global

// 核心配置:注入 global 全局变量,映射到浏览器的 window
  define: {
    // 解决 global is not defined
    global: 'window',
    // 可选:如果后续遇到 process is not defined,补充这个映射
    'process.env': JSON.stringify({ NODE_ENV: 'development' })
  },

5、Uncaught ReferenceError: Cannot access 'keepaliveAgent' before initialization

 

 

 

 

 

 

 

 

 

 

 

 

 
posted @ 2026-01-13 09:35  别苦了颗脑袋  阅读(2)  评论(0)    收藏  举报