Constant imported from TypeScript is not defined

I have encountered an issue in my Vue.js project with TypeScript. I defined a constant named serverUrl in one file for HTTP declarations, and then imported it into another file where the AuthService class is defined. Strangely, this constant appears as UNDEFINED when accessed in either the property declaration or constructor of AuthService. However, it works fine within the login() function. What could be causing this problem? Below are snippets from my files:

import axios, { AxiosError, AxiosRequestConfig } from 'axios';

export const serverUrl = 'http://localhost:63523';       // Definition of serverUrl Constant

export const http = axios.create({   timeout: 20000,   headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'   } });

And here is the AuthService file:

import { http, serverUrl } from '@/services/http';

export class AuthService {

  private authUrl: string = serverUrl + '/' + 'auth/login';    // Issue with serverUrl being UNDEFINED

  constructor() {
    this.authUrl = `${serverUrl}/auth/login`;                   // Issue with serverUrl being UNDEFINED
  }

  public login(login: string, password: string ) {
    const authUrl2: string = serverUrl + '/' + 'auth/login';   // serverUrl displayed correctly here
    return http.post(authUrl2, {login, password});
  }
}

export const authService = new AuthService();

Answer №1

During the discussion in the comments, it was pointed out that the variable serverUrl was not properly injected into the file AuthService due to a circular dependency existing between these two files (which was not evident based on the provided code).

To resolve this issue, it is necessary to eliminate the circular dependency between these two files so that the variable serverUrl can be imported correctly.

Answer №2

My issue was unique in that I didn't have any circular imports or dependencies to deal with.

The problem arose from me importing a precompiled barrel index.ts file from another module (MODULE B) into my codebase (MODULE A). This file was located in the dist folder and had a package.json pointing to it, which caused it to overshadow the actual fresh index.ts.

To solve this issue, I simply removed the built dist folder, allowing the TypeScript compiler to correctly import the updated index.ts afterwards.

Check out the code snippet below for reference:

MODULE A

code:

import { TAG_PROPERTY_NAME, IFormActivity } from "@colabo-flow/i-core";

// `undefined` as we were importing old `dist/index.js` file without `TAG_PROPERTY_NAME` exported, instead of the new `index/ts` file with `TAG_PROPERTY_NAME` exported
console.warn(`TAG_PROPERTY_NAME: ${TAG_PROPERTY_NAME}`);

tsconfig.json:

{
    "compilerOptions": {
        "paths": {
            "@colabo-flow/i-core": [
                "<REST_OF_THE_PATH>/puzzles/flow/core",
            ],
            // ...
        },
        // ...
    },
    // ...
}

MODULE B

package.json:

{
    "main": "dist/index.js",
    "module": "dist/index.js",
    // ...
}

index.ts:

export const TAG_PROPERTY_NAME = "tags";
// ...

Answer №3

Although this might seem specific, I encountered a similar problem where all imports from my "voices.ts" file were coming up as undefined.

After some investigation, I discovered that there was another file named "voices.json" in the same directory.

Ultimately, renaming one of the files resolved the issue completely.

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

Updating the position of an element in HTML is not possible

For my webpage, I am attempting to adjust the position of all images that are displayed. Despite trying to change the position of a single image using the DOM method, I have run into a problem where the position does not update as expected. Although the co ...

"Troubleshooting: Child Component Not Reflecting Changes in UI Despite Using Angular

My child component is designed to display a table based on a list provided through @Input(). The data is fetched via http, but the UI (child component) does not update unless I hover over the screen. I've seen suggestions about implementing ngOnChange ...

Angular2rc1's DynamicComponentLoader function LoadIntoLocation allows dynamic loading of components

Can someone explain how to utilize the LoadIntoLocation method in Angular2 rc 001? In DynamocComponentLoader, I have only encountered two methods: loadAsRoot and loadNextLocation. Any help would be appreciated. Thank you! ...

What is the correct way to input the 'name' HTML attribute in an Ant Design select element?

I am facing an issue with the 'name' attribute in my Ant Design Select component. When trying to set the 'name' attribute, I encountered an error message that is causing issues. https://i.stack.imgur.com/Lzb4t.png Ant Design Select Co ...

Is there a user-friendly interface in Typescript for basic dictionaries?

I'm not inquiring about the implementation of a dictionary in Typescript; rather, I'm curious: "Does Typescript provide predefined interfaces for common dictionary scenarios?" For instance: In my project, I require a dictionary with elements of ...

Looking to resolve a module-specific error in Angular that has not been identified

While practicing Angular, I encountered an error during compilation: Module not found: Error: Can't resolve './app.component.css' in 'D:\hello-world-app\src\app' i 「wdm」: Failed to compile. This is my app.compo ...

Deactivating PrimeNG checkbox

I am currently facing an issue with disabling a PrimeNG checkbox under certain conditions by setting the disabled property to true. However, whenever I click on the disabled checkbox, it refreshes the page and redirects me to the rootpage /#. To troublesh ...

What is the best way to prevent jest.mock from being hoisted and only use it in a single jest unit test?

My goal is to create a mock import that will be used only in one specific jest unit test, but I am encountering some challenges. Below is the mock that I want to be restricted to just one test: jest.mock("@components/components-chat-dialog", () ...

Validating the observable subscribe input parameter

Why is there no error or warning displayed in the subscribe parameter when defining the wrong parameter type in tsconfig? For example, in the correct code below, if 'user' is of type 'UserDto', VS Code will identify it correctly. Howev ...

The error message "Cannot find property 'X' on type 'number' in React TypeScript" is appearing

When iterating over the list of brands, I am facing an issue where the brand properties are not loading properly. During this time, the indexed array is displayed as a skeleton structure. While JavaScript handles this situation well, TypeScript encounter ...

Having trouble with Webpack unable to locate the necessary import for Typescript type resolution? Need help resolving this issue?

My current project is utilizing typescript and has been constructed using webpack. Within my project, there exists a typings file originating from a third-party library, located at node_modules/@types/libname/custom.d.ts. This particular file contains a n ...

Error in integrating ng2-bootstrap pagination with a bootstrap table

I am currently working on incorporating the ng2-bootstrap pagination component with a bootstrap table. The bootstrap table I have is populated using the ngFor directive: <tr> <th *ngFor="#col of cols">{{col.header}} </tr> </thead ...

What steps can I take to troubleshoot and repair my accordion feature within an Angular project?

As a newcomer to Angular, I recently attempted to create an accordion component but encountered unexpected behavior. Here is the HTML code for my attempt: <div class="faq-item-container"> <h1 class="mt-1 mb-5"><strong>Frequently A ...

An issue has occurred where all parameters for the DataService in the D:/appangular/src/app/services/data.service.ts file cannot be resolved: (?, [object Object])

Upon running the command ng build --prod, an error is encountered. Error in data.service.ts: import { BadInput } from './../common/bad-input'; import { AppError } from './../common/app-error'; import { Injectable } from '@angular ...

While Typescript has the ability to infer recursive functions, it unfortunately cannot infer recursive types

Typescript has the ability to automatically determine the type of a recursive function: /** * Typescript correctly infers the type as * * const referencesSelf: () => ... * * This indicates recursion within the function */ const referencesSelf = () ...

What causes a statically declared state to be null in the lifecycle of an object in Typescript and JSX?

In one of my projects, I am utilizing Redux and declaring my components like this: class Foo extends React.component<any, any> { public static state: any = { bar: '' } } const mapStateToProps = (state) => { return {} } expor ...

Disabling the update button once all required fields are filled when clicking the edit button in Angular2

In my application, I have both a Save and an Update button. I am using reactive forms where the Save button is disabled if any of the validator fields are not filled, and it gets enabled once all validator fields are filled. However, in the case of the Upd ...

Typescript: Mongoose encountered an error when trying to convert value to ObjectId for the specified path "_id"

Whenever I intentionally use postman to request a wrong product ID, the application crashes. Cause The error is not being caught by my error-handler middleware. Route /* retrieves a single product */ router.get("/:id", async (req: Request, res: Respons ...

Exploring the Depths of Observables in Angular2 Guards

I have a Guardian overseeing a specific route. Within the canActivate method, I am trying to perform two HTTP requests, with the second request being dependent on the response of the first one. However, it seems like the second request is not being trigger ...

Generate TypeScript types automatically based on an object

I'm working with a code snippet that looks like this: import { ApolloClient } from '@apollo/client'; type F = typeof FeaturesManager.features.warrants export class FeaturesManager { static features = { warrants: Symbol('WARRANTS ...