After compiling, global variables in Vue.js 2 + Typescript may lose their values

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.

Answer №1

After relocating the prototyping parts from main.ts to App.ts file, I have successfully resolved the issue.

I am not completely certain if this is considered the correct "Vue.js way" of addressing the problem, as I have previously defined it in the main.js file - however, back then I was using JavaScript and it was functioning as expected without any issues.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the capabilities of the Javascript Fetch API by making requests for binary Float32Array data with multiple

I need to fetch multiple 32-bit float values from different parts of a large binary file using range requests. This requires specifying multiple ranges in the request. fetch("http://example.com/largeBinaryFile.bin", { headers: { ' ...

Organize a collection of items in AngularJS

Consider the following array: var members = [ {name: "john", team: 1}, {name: "kevin", team: 1}, {name: "rob", team: 2}, {name: "matt", team: 2}, {name: "clint", team: 3}, {name: "will", team: 3} ]; I want to create an unordered list for each ...

Utilizing TypeScript generics to accurately extract type information from state during reduction

In the context of a state reducer presented as follows: const anObject = { fruit: 'Apple', today: new Date(), } function reducer(state, stateReducer) { return stateReducer(state); } const fruit = reducer(anObject, state => state.fruit ...

How to pass a method from a child component to a parent component in Vue.js

Does anyone know how to pass a function from the child component to the parent component? I have a modal in the parent component with cancel and submit buttons. When either button is clicked, I want to close the child component. I tried setting "show" in t ...

What are the steps to employ a query string to display a specific image?

If I understand correctly, I can utilize a query string and parse it to display certain information. How would I apply that concept to load a specific image? https://codepen.io/anon/pen/qYXexG <div id="gallery"> <div id="panel"> <img ...

Learn how to utilize the "is" status in Postma within your code, even when this particular status is not included in the response

Service.ts Upon invoking this function, I receive a JSON response similar to the following: public signupuser(user: Users): Observable<boolean> { let headers = new Headers(); headers.append('Content-Type', 'application/json&a ...

CKEditor directive in AngularJS does not properly enforce the maxlength attribute in textarea

I am currently working on an AngularJS application with the CKEditor plugin. I have created a directive for CKEditor and everything seems to be functioning properly. However, I am facing an issue where I need to limit the character length to 50. I tried us ...

What is the best way to incorporate Vue.component with modules or Vue CLI?

I'm having trouble figuring out the correct way to declare a Vue.component within export default. This issue arises from following a tutorial on vuejs.org. https://i.sstatic.net/PH3VN.png Instead of using var app = new Vue, I am implementing it as ...

Change an ISO date format to DD:MM:YYYY HH:MM using Angular

I currently have my date in this format: 2022-11-21T21:07:56.830-07:00 However, I am looking to convert it to the following format: 21/11/2022 07:56 ...

Having trouble with the functionality of a Chrome extension content-script JavaScript that is set to run at document_end

Currently, I am in the process of developing a Google Chrome extension that is designed to hide the "news" section located on the right-hand side of Facebook, along with the ads displayed on the right side. Additionally, the background color is meant to be ...

If you want to retrieve the calculated value of a div using jQuery

I have a scenario where I have 3 list items (li) under an unordered list (ul). I am interested in finding the height of these list items, but without explicitly defining their height. So far, when inspecting with Firebug, I noticed that the computed height ...

Exploring the possibilities of integrating CSS and JavaScript in Node.js with Express

Here is the folder structure I am working with: lifecoding |login2 |index.html |css style.css |js index.js I have all the necessary modules installed for express to work properly. However, when I try to set the static path as shown below, it keeps ...

Jquery trigger causing href links to malfunction

Here is a JavaScript example: var sampleFunction = function(){ return { initialize : function(data) { this.sendRequest({ action : 'login' }); }, loginAction : function() { ...

steps for including preset text in an input field within a form on WordPress

I am currently utilizing a WordPress plugin that automatically generates a form in the admin area based on user input. The form includes five fields that require URL validation. Users have the option to enter optional link text which will be displayed as t ...

Utilizing AJAX and setInterval Techniques for Efficient handling of window.location.hash

//Collecting AJAX links var ajaxLink = $("#logo, .navLink, .tableLink, .footerLink"); //Storing the recent state as null (because there is none yet) var recentState = null; //Initializing the page state based on the URL (bookmarking compatibility) window ...

The presence of asynchronous JavaScript can lead to errors due to missing functions in JavaScript

I've encountered an issue with a jQuery script that I modified by adding an ASYNC attribute. Surprisingly, it functions correctly in Firefox but encounters intermittent failures in both Chrome and IE browsers. Here's the PHP code snippet respons ...

Having trouble with vscode [ctrl+click] on 'vue single-file components' and 'go to definition'? It's not working for me

// src/ui/tabbar/Index.vue <template> <div> my-tabbar component here </div> </template> // src/ui/index.js import MyTabbar from './tabbar/Index.vue' export default { install(Vue) { Vue.component(MyTabbar.na ...

When using @click as a link, it results in an

I'm attempting to create a clickable row in a datatable that functions as a link. Placing a standard <nuxt-link> within a <td> works fine, but wrapping the entire <tr> disrupts the table layout. Next, I tried using @click with a met ...

Transforming RGB Decimal Color to HEX RGB Color in Three.js

Currently, I am facing a challenge in my task involving colors while working with three.js, a JavaScript library. In this particular task, I need to convert decimal color codes (e.g. 12615680) into formats like #FF0000 or 0xFF0000. I am seeking a JavaScr ...

tips for sending types as properties in a versatile component

I am facing a challenge with passing types as props to a reusable component. I have a component where I pass rows and headings as props, but I need to find a way to pass types as props as well. Below is the code for my reusable component: import { TableCe ...