I am currently working on a Vue.js 2 project that uses Typescript. I have declared two variables in the main.ts
file that I need to access globally throughout my project:
// ...
Vue.prototype.$http = http; // This library is imported from another file and contains various methods such as `get`, `post`, etc.
Vue.prototype.$urls = urls; // This is a JSON object also imported from another file
new Vue({
store,
render: (h) => h(App),
}).$mount('#app');
In one of my components, let's refer to it as User
, I have the following code block inside the mounted
hook:
mounted(): void {
this.$http.get(`${this.$urls.getUser}/${this.userId}`);
}
Everything works perfectly when I run the local server using the command npm run serve
. However, when I build the app with the command npm run build
and try to access it on the server or through the index.html
file on my hard drive, I encounter the following error:
TypeError: Cannot read property 'get' of undefined
at VueComponent.value (user.ts:62) // <-- This line corresponds to $http.get in the `mounted` hook
I am unsure about how to proceed with this issue. I have attempted to add these global values to different places without success. For instance, in the http.d.ts
file, I added the following:
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
}
}
(I have also created a similar declaration file for urls.d.ts
)
UPDATE #1:
Another approach I tried was adding the following to my main.ts
file:
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);
However, this did not resolve the issue (same error persists).
UPDATE #2:
I also imported the http
utility into my user
component and added a console.log
statement within the existing mounted
callback:
console.log(http, this.$http)
While running on localhost, it logs the same value twice. But when I create a build, it logs:
Module {__esModule: true, Symbol(Symbol.toStringTag): "Module"}, undefined
A similar scenario occurs if I add console.log(urls, this.$urls)
- the imported module gets logged while the prototyped one returns undefined
.
If you have any insights or suggestions, I would greatly appreciate your help.