如何扩展 Vue 的全局属性(如 $http)的类型声明?
解读
在国内一线/二线大厂的 Vue3 项目中,90% 会把网络请求、埋点、国际化等能力挂载到全局属性(app.config.globalProperties)上,以便在任意组件内通过 this.http 会报“Property '$http' does not exist on type ComponentPublicInstance...”。
面试时,面试官想确认两点:
- 你是否知道“声明合并”这一 TypeScript 原生机制;
- 你是否能把声明文件放到正确的目录(types/xxx.d.ts)并保证构建工具(Vite / Webpack)能收录。
答不出来会被直接判定为“只能写 JS,不能维护 TS 大型项目”。
知识点
- 模块增强(Module Augmentation)与接口合并(Interface Merging)
- @vue/runtime-core 包导出的 ComponentCustomProperties 接口
- 三斜杠指令 /// <reference types="vite/client" /> 与 tsconfig.json 的 include 字段
- 全局属性与 provide/inject 的取舍:全局属性适合“稳定、全局、单例”场景,provide/inject 适合“插件内部按需注入”
- 类型安全链条:声明 → 编译 → 运行时,必须三点一致,否则出现“编译通过、运行 undefined”的线上事故
答案
步骤一:创建类型文件
在 src/types 目录下新建 global.d.ts(文件名随意,只要被 tsconfig 收录即可):
import type { AxiosInstance } from 'axios'
declare module '@vue/runtime-core' {
interface ComponentCustomProperties {
$http: AxiosInstance
$track: (event: string, payload?: any) => void
}
}
步骤二:确保文件被编译
tsconfig.json 里加入
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"]
步骤三:注册全局属性
main.ts 中:
import axios from 'axios'
const app = createApp(App)
app.config.globalProperties.$http = axios
app.mount('#app')
步骤四:验证
在任意组件:
export default defineComponent({
mounted() {
// 此时 this.$http 已具备完整 Axios 类型提示
this.$http.get('/api/user').then(res => console.log(res.data))
}
})
注意:
- 必须 import 某类型(如 AxiosInstance)后再 declare,否则 TypeScript 会报“无法找到名称”的错误;
- 若使用 Vue2 + ts-loader,需改为 declare module 'vue/types/vue' 并给 Vue 接口做合并;
- 不要把全局属性声明写在 shims-vue.d.ts 里,该文件仅用于 *.vue 单文件组件的模块声明,放一起会导致团队协作冲突。
拓展思考
- 规模更大时,建议把 $http 封装成 useRequest() 组合式函数,不再依赖 this,既避免全局污染,也能让 tree-shaking 更彻底;
- 如果项目同时支持 SSR(Nuxt3),需在 client 与 server 两端分别注入类型,否则 server 端会报“$http 未定义”;
- 对于微前端场景,主应用与子应用都扩展了同名 $http,需通过“命名空间+模块联邦”做隔离,防止类型相互覆盖;
- 面试加分项:可以补充“如何给全局属性写单元测试”。示例:使用 vitest + @vue/test-utils,手动 app.config.globalProperties.http 被正确调用,从而证明“类型声明 + 运行时”一致性。