首页 > 解决方案 > Vue.js 2 + Typescript - 全局变量在构建后变得未定义

问题描述

我有一个带有 Typescript 的 Vue.js 2 项目。在main.ts文件中,我声明了 2 个变量,我想在我的项目中全局访问它们:

// ...
Vue.prototype.$http = http; // this is the library imported from another file, contains various methods such as `get`, `post` etc.
Vue.prototype.$urls = urls; // this is JSON object, also imported from another file
new Vue({
  store,
  render: (h) => h(App),
}).$mount('#app');

在我的一个组件中,我们称它为User我有以下mounted代码块:

mounted(): void {
  this.$http.get(`${this.$urls.getUser}/${this.userId}`);
}

当我运行本地服务器(通过npm run serve命令)时一切正常,但是当我创建应用程序构建(通过npm run build命令)并在服务器上输入应用程序(或index.html我的硬盘上的文件)时,我收到以下错误:

TypeError: Cannot read property 'get' of undefined
    at VueComponent.value (user.ts:62)  // <-- this line is the one with $http.get from `mounted` hook

我不确定如何进行此操作,我盲目地尝试将这些全局值添加到各个位置,例如在http.d.ts文件中我有以下内容:

import { KeyableInterface } from '@/interfaces/HelperInterfaces';
import Vue from 'vue';

declare module 'vue/types/vue' {
  interface VueConstructor  {
    $http: KeyableInterface;
  }
}

declare module 'vue/types/vue' {
  interface Vue  {
    $http: KeyableInterface;
  }
}

declare module 'vue/types/options' {
  interface ComponentOptions<V extends Vue> {
    http?: KeyableInterface
  }
}

(我也urls.d.ts用类似的代码创建过)

更新#1:

我也尝试过以下方法 - 在我的main.ts文件中:

const helperModules = {
  /* eslint-disable-next-line @typescript-eslint/no-explicit-any */
  install: (vueInstance: any) => {
    vueInstance.prototype.$http = http;
    vueInstance.prototype.$urls = urls;
  },
};

Vue.use(helperModules);

但它仍然不起作用(同样的错误)。

更新#2:

我还将http实用程序导入到我的user组件中,并console.log在现有mounted回调中添加了以下内容:

console.log(http, this.$http)

在处理 mylocalhost时,它会返回两倍相同的值,但是当我创建构建时,它会返回:

Module {__esModule: true, Symbol(Symbol.toStringTag): "Module"}, undefined

类似的事情发生了,当我添加console.log(urls, this.$urls)- 导入的模块被记录,而原型返回时undefined

有什么想法吗?将不胜感激任何帮助。

标签: javascripttypescriptvue.jsvuejs2

解决方案


最后,我通过将原型部件从文件移动main.tsApp.ts文件来克服了这个问题。

我不能 100% 确定它是否是解决这个问题的有效“Vue.js 方式”,因为我一直在main.js文件中声明 - 但我当时使用的是 JavaScript,它按预期“正常工作”。


推荐阅读