Vue 2 + Webpack 外链迁移 Vite 时,Vue.prototype 为什么会「丢」

Vue 2 + Webpack 外链迁移 Vite 时,Vue.prototype 为什么会「丢」

真实案例笔记 · Vue 2 / Webpack externals / Vite alias

本文以一个真实的 Vue 2 后台项目(CDN 引入 Vue + webpack externals)为案例, 解释迁移 Vite 后 Vue.prototype.xxx 读不到的根因,并区分「编译器用的 Vue」和「浏览器里跑的 Vue」。

写给谁看

  • 正在把 Vue 2 + webpack 老项目迁到 Vite
  • 依赖仍挂在 index.html 的 CDN 上(vue / vuex / element-ui 等)
  • 业务里大量使用 Vue.prototype.G / this.G 这类全局挂载
  • 遇到「明明挂了属性,组件里却是 undefined」或表现随机

如果你的项目一开始就是 npm 安装 Vue、没有 CDN 双轨,这篇里的「双实例」问题会轻很多, 但「编译时 vs 运行时」的区分仍然有用。

一句话结论

Webpack 用 externals 保证全项目只有一份运行时 Vue;Vite 默认可能再解析出 node_modules 里的另一份。Vue.prototype 挂在哪一份构造函数上, 只有那一份创建的实例能读到。@vitejs/plugin-vue2 用的 Vue 2.7 主要是编译器; 让 prototype「丢失」的,通常是运行时不小心加载了第二份 Vue。

1. Vue.prototype 到底挂在哪

Vue 2 组件实例来自构造函数。关系可以理解成:

构造函数 → 原型 → 实例

Vue 构造函数 import Vue from 'vue' 拿到的那一份
↓
Vue.prototype 所有实例共享 · 在这里挂 G
↓
new Vue() / 组件 this this.G 能读到

入口常见写法:

import Vue from 'vue'

Vue.prototype.G = {
  permission: {},
  userInfo: undefined,
  // ...
}

含义是:给当前这份 Vue 函数对象的原型挂属性。 之后凡是用这份 Vue 创建的实例,都能通过 this.G 访问。

prototype 挂在「某一个具体的 Vue 构造函数」上,不是挂在「名叫 vue 的抽象概念」上。

如果运行时出现两个不同的 Vue(VueA !== VueB),就有两套互不相通的原型链。

2. Webpack 时代为什么很少出问题:externals 强制单例

典型老后台:index.html 先拉 CDN,再跑打包出来的业务脚本。

<!DOCTYPE html>
<html>
<head>
  <title>后台</title>
</head>
<body>
  <div id="app"></div>

  <!-- 1. 先有全局构造函数 -->
  <script src="https://cdn.example.com/vue/2.5.22/vue.runtime.min.js"></script>
  <script src="https://cdn.example.com/vuex/3.0.1/vuex.min.js"></script>
  <script src="https://cdn.example.com/vue-router/2.8.1/vue-router.min.js"></script>
  <script src="https://cdn.example.com/element-ui/2.7.2/index.js"></script>
  <script src="https://cdn.example.com/axios/0.18.0/axios.min.js"></script>

  <!-- 2. webpack 业务包:import 'vue' 被 externals 指到 window.Vue -->
  <script src="./app.js"></script>
</body>
</html>

webpack 配置:

externals: {
  vue: 'Vue',
  vuex: 'Vuex',
  'vue-router': 'VueRouter',
  'element-ui': 'ELEMENT',
  axios: 'axios'
}

业务照常写:

import Vue from 'vue'
Vue.prototype.G = { /* ... */ }
new Vue({ router, store, render: h => h(App) })

打包时 webpack 不会把 vue 打进 bundle,而是改成读全局 Vue:

Webpack 强制单例

CDN <script> 先创建 window.Vue
↓ externals 重写 import
唯一构造函数 window.Vue G / Vue.use / new Vue 全走这里
环节 实际用的是
HTML <script> window.Vue(CDN)
import Vue from 'vue' 同一份 window.Vue
Vue.use(ElementUI) / new Vue() 同一份
Vue.prototype.G 挂在这一份上

所以不是「没有双 Vue 风险」,而是 externals 在工程上强制了单例。

3. Vite 换了一套模块规则

Vite 开发态按原生 ESM 解析。页面往往变成:

<!DOCTYPE html>
<html>
<body>
  <div id="app"></div>

  <!-- CDN 仍在:VueA = window.Vue(例如 2.5.22) -->
  <script src="https://cdn.example.com/vue/2.5.22/vue.runtime.min.js"></script>
  <script src="https://cdn.example.com/element-ui/2.7.2/index.js"></script>

  <!-- Vite 模块入口:可能再解析出 node_modules 里的 VueB -->
  <script type="module" src="/vite/entry.js"></script>
</body>
</html>

若未配置 alias,业务里的 import Vue from 'vue' 常常落到:

node_modules/vue/dist/vue.runtime.esm.js

危险:同一页面两份运行时

VueA = window.Vue CDN 2.5.22 · 部分插件仍在这
VueB = npm ESM node_modules 2.7.x · G 挂在这
↓ A !== B
两套 prototype 互不相通 this.G → undefined
const VueA = window.Vue          // CDN
const VueB = /* 从 npm 模块图进来的 Vue */
console.log(VueA === VueB)       // false
// main.js —— 若 import 到的是 VueB
import Vue from 'vue'
Vue.prototype.G = { permission: {}, userInfo: null }

// 若根实例或某些插件实际绑在 VueA 上
this.G                  // undefined
window.Vue.prototype.G  // 可能也没有(G 挂在 B 上)

表现会很「玄学」:登录写了 G.userInfo,某个页面读不到; 控制台手敲有值,组件里没有——因为你看的不是同一份 Vue。

根因不是 Vue.prototype API 坏了,而是单例被拆成了两份。

4. 容易混在一起的两点:编译器 2.7 vs 运行时 2.5

迁 Vite 时会装 @vitejs/plugin-vue2,它依赖 Vue 2.7 的 compiler-sfc。很多人会以为:

「prototype 挂在 CDN 2.5 上,plugin 用的是 2.7,所以 2.7 上没有 G 就报错。」

这个理解不准确。 要拆开:

编译时 vs 运行时

编译时 · Node .vue → Vue 2.7 compiler-sfc → 渲染函数 只是翻译器,不挂浏览器 prototype
运行时 · 浏览器 import Vue 决定用哪份构造函数 new Vue / this.G 走那份 prototype
角色 典型版本 职责 和 prototype.G
编译器 npm 2.7(给 plugin 用) 编译 .vue 基本无关
运行时(期望) CDN window.Vue 创建实例 G 应挂在这里
运行时(事故) 又混入 npm 那份 第二套实例 G 在 A,实例是 B → 读不到

版本 2.5 / 2.7 不一致可能带来别的边角问题,但和「G 丢失」相比,是第二层问题。 第一层永远是:运行时有几份 Vue?

5. 三种形态对照

5.1 Webpack:安全单例 ✓
CDN:window.Vue
↓ webpack externals
业务 import / G / new Vue 同一条链
<script src="cdn/vue.runtime.min.js"></script>
<script src="./app.js"></script>
5.2 Vite 未正确 alias:危险双实例 ✗
VueA:CDN插件可能还在这
VueB:node_modulesmain.js 把 G 挂在这
<script src="cdn/vue.runtime.min.js"></script>
<script type="module" src="/src/main.js"></script>
5.3 Vite + shim:重新变回单例 ✓
CDN:window.Vue
↓ alias → shims/vue.js → export default window.Vue
业务 import 全部拿到 VueAnpm vue@2.7 只留在 Node 编译 .vue
// vite/shims/vue.js
export default window.Vue

这和 webpack 的 externals: { vue: 'Vue' } 是同一设计, 只是从「打包期替换」变成了「解析期别名」。

6. 为什么强依赖 Vue.prototype 的项目会更痛

不少后台会把「全局口袋」挂在原型上,例如:

Vue.prototype.G = {
  pageTitle: '冻品云',
  permission: {},
  userInfo: undefined,
  routers,
  printParam,
  // ...
}

权限、登录态、打印参数、地图 AK 都从 G 读。 它不是 Vuex 模块,而是挂在构造函数上的全局状态。

双 Vue 时的典型症状:

  1. 登录后写入 G.userInfo,某页读不到
  2. this.G 为 undefined,控制台里 Vue.prototype.G 却有值
  3. Element / Router / Vuex 表现异常(它们也必须和根实例同一份 Vue)

可以把 Vue.prototype.G 当成「双实例问题的放大镜」——业务越依赖它,迁移时越早爆出来。

7. 排查清单(建议收藏)

在浏览器控制台:

// CDN 是否存在
typeof window.Vue

// 业务拿到的是否同一份(可在 main.js 临时打日志)
import Vue from 'vue'
console.log('same as CDN?', Vue === window.Vue)

// prototype 是否一致
console.log(Vue.prototype.G)
console.log(window.Vue.prototype.G)
console.log(Vue.prototype.G === window.Vue.prototype.G)

期望(shim 正确时):

  • Vue === window.Vue → true
  • 两边的 G 是同一引用

再看 Network:是否加载了 /node_modules/.vite/deps/vue.js 一类预构建文件。 若有,说明 vue 仍被 optimizeDeps 打进了一份。

8. 防护与演进路径

短期:继续 CDN,Vite 只做 dev

  1. resolve.alias:vue → export default window.Vue
  2. 同样处理 vuex / vue-router / axios / element-ui
  3. optimizeDeps.exclude: ['vue', 'vuex', 'vue-router', 'element-ui']
  4. resolve.dedupe: ['vue']
  5. 如有 vue/dist/... 深路径 import,一并 alias 拦掉

目标只有一个:浏览器里永远只有一个 Vue 构造函数。

中期

CDN 的 Vue runtime 升到与编译器一致的 2.7.x,减少版本差带来的边角差异。

长期:全量 Vite

页面不再外链 Vue,改为由打包结果自行提供运行时:

<!DOCTYPE html>
<html>
<body>
  <div id="app"></div>
  <!-- 不再 <script src="cdn/vue..."> -->
  <script type="module" src="/assets/index-xxxxx.js"></script>
</body>
</html>

两阶段更稳

阶段 A dev:vite + 生产仍 webpack
→
阶段 B 源码 ESM 化后 vite build

此时 Vue.prototype 反而更简单;代价是改 index.html 与缓存/发布策略。

9. 附录:迁移时和「模块形态」相关的相邻坑

Vue.prototype 只是最「业务可见」的坑之一。 同一类「Webpack 特化 → 原生 ESM」还包括:

现象 常见原因
doesn't provide an export named 'default' 文件是 module.exports 或纯副作用、没有 export default
state.sidebar is undefined require.context 转 import.meta.glob 后 key 变成 modules/sidebar
路由懒加载失败 require.ensure 需改为 () => import()
样式 / PostCSS 报错 旧版 autoprefixer 与 Vite 的 PostCSS 8 不兼容

写迁移总结时,可以把主题定成: 不是 Vite 不能跑 Vue 2,而是要把隐藏的 webpack 约定显式化。

10. 收束

  • Vue.prototype 绑定的是具体那一份 Vue 构造函数
  • Webpack externals + CDN 用工程手段保证了单例
  • Vite 若同时碰 CDN 与 node_modules/vue,就会双实例,表现为 G / 插件「丢失」
  • @vitejs/plugin-vue2 的 2.7 主要是编译器;别和运行时 CDN 混为一谈
  • 修复思路:shim / alias / exclude,让运行时重新变回「只有一份 Vue」

如果你也在迁老 Vue 2 后台,欢迎用文中的 Vue === window.Vue 检查做第一刀——往往比对着业务报错猜要快。