What is the reason for VS Code recognizing an import as valid while WebPack does not approve it?

I believe the root of the problem lies in the version of WebPack I am using (

"webpack-cli": "3.3.11"
). Before embarking on another round of debugging to upgrade WebPack (attempted version 5 but faced issues due to lack of a config file), I want to confirm my assumption. I seem to be pushing against the boundaries of the instructions, skimming over the manual as I go along.

Within tsconfig.base.js, the following configuration is present:

"baseUrl": ".",
"paths": {
  "@/*": ["src/*"]
}

(The rationale behind using a separate tsconfig.base.json is explained in the linked question below.)

Additionally, this import can be found:

import { RegistrationStepManager } from "@/helpers";

within the file

./src/some/path/RegistrationStepper.tsx
.

Upon running npm start with CRA and react-scripts v4.0.3, an error is displayed without causing a crash:

Failed to compile.

./src/some/path/RegistrationStepper.tsx
Module not found: Can't resolve '@/helpers' in '/my-path/my-project/src/some/other/path'.

Despite VS Code tooltips and autocompletion indicating correct importation, there are only minor warnings, no red underlines.

The suspicion is that the alias for "@/*" isn't functioning properly, although VS Code seems to handle it flawlessly, suggesting a potential bug.

How does TypeScript interact with WebPack in light of such failures? Is upgrading to WebPack 5 necessary?

An additional query within the same timeframe and codebase has been raised by me: How can I import an enum through an intermediate TS file?.

Thank you.

Update 1

I stumbled upon this post, prompting me to transition from CRA to standalone WebPack since my project holds more significance than mere experimentation. Could you possibly recommend a migration guide from CRA to WebPack? The initial issue in this inquiry may stem from a deficient WebPack setup. I possess an outdated WebPack configuration file that could be contributing to the problem.

Answer №1

While working on my project, I realized that the WebPack config file I had set up was not being utilized because I was actually using CRA. To address this issue, I decided to incorporate react-app-rewired and WebPack v4 as a temporary solution before transitioning to a "pure" WebPack setup. In the config-overrides.js, I made the following changes:

const TsconfigPathsPlugin = require("tsconfig-paths-webpack-plugin");

module.exports = {
  webpack: function(config, env) {
    return {
      ...config,
      resolve: {
        ...config.resolve,
        plugins: [
          ...config.resolve.plugins,
          new TsconfigPathsPlugin({
            extensions: [".js", ".jsx", ".ts", ".tsx"],
          }),
        ],
      },
    };
  },
};

After switching to react-app-rewired and implementing these modifications, I successfully resolved the Failed to compile. error. This adjustment also addressed an issue discussed in How can I import an enum through an intermediate TS file?.

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

Having trouble generating a mock constructor for the user model

While attempting to simulate my user model in order to test my service, the nest console is throwing a TypeError. I am unsure of how to properly 'emulate' the constructor of the user model. user.service.spec.ts import { Test, TestingModule } fro ...

The 'catch' property is not found within the type 'PromiseLike<void>'

Help! I'm encountering a Typescript Error. An issue is arising with the 'catch' property on type 'PromiseLike<void>'. I am using Ionic and facing an error in the line containing catch: sendrequest(req: connreq) { var p ...

Performing actions simultaneously with Angular 2 directives

My custom directive is designed to prevent a double click on the submit button: import { Directive, Component, OnInit, AfterViewInit, OnChanges, SimpleChanges, HostListener, ElementRef, Input, HostBinding } from '@angular/core'; @Directive({ ...

Exporting constants using abstract classes in TypeScript files

In my Typescript files, I've been exporting constant variables like this: export const VALIDATION = { AMOUNT_MAX_VALUE: 100_000_000, AMOUNT_MIN_VALUE: 0, DESCRIPTION_MAX_LENGTH: 50, }; My constant files only contain this one export without any ...

Timeout with Promise

I'm looking to enhance my understanding of working with promises by rewriting this function to resolve the promise instead of resorting to calling the callback function. export const connect = (callback: CallableFunction|void): void => { LOG.d ...

Experimenting with a VSCode extension that requires the act of launching a folder/workspace

Currently, I am developing a custom VSCode extension that considers the path of the file being opened within the workspace. To create a reproducible test scenario, I want to open the test folder itself in VSCode and then proceed to open the test file with ...

Is it possible to ensure that the Python debugger pauses before exiting every time?

While I am able to set breakpoints, there are times when I simply need to examine some variables after running a test. Is there a method in vscode to debug pytest tests without manually setting breakpoints or including pause statements, allowing it to aut ...

Is it possible to verify .0 with regular expressions?

In my project, I have a field that requires whole numbers only. To validate this, I used a regex validation /^\d{1,3}$/ which successfully validates whole number entry and rejects decimal points starting from .1. However, I encountered an issue where ...

Using a snapshot test with MenuItem from material-ui is not compatible with Jest

I am facing an issue while trying to perform a snapshot test with jest on a component that utilizes typescript, react, and material-ui. Specifically, the MenuItem component from material-ui is throwing an Invariant Violation: getNodeFromInstance: Invalid a ...

Creating a dynamic dropdown menu triggered by a button click using Angular

I am a beginner in Angular (typescript) and I am facing some challenges in adding a new dropdown menu when a user clicks a button. My main struggle is creating additional attribute fields. I'm considering keeping track of the newly added dropdowns wit ...

Unselect all options in Angular's multiple selection feature

Objective: My goal is to ensure that when I invoke the myMethod() function, all options are unselected. Current Issue: Currently, calling myMethod() will only deselect the last option, leaving the others selected if they were previously selected. Possibl ...

Is there a way to assign values of object properties to the corresponding object in TypeScript?

I'm looking for a solution in TypeScript where I can map values of object keys to the same object, and have IntelliSense work correctly. Here's an example that illustrates what I need: const obj = getByName([ { __name: 'foo', baz: &ap ...

Issue encountered: UnresolvedSchemeError while building module on Next.js version 13 with sentry

After setting up a Next.js 13 project with automated installation of Sentry, I encountered an issue where the file path C:\Users\myuser\Desktop\Work\project\sentry.server.config.ts was causing problems during compilation. It s ...

Guide to retrieving the previous URL in Angular 2 using Observables

Can someone help me retrieve my previous URL? Below is the code snippet I am working with: prev2() { Promise.resolve(this.router.events.filter(event => event instanceof NavigationEnd)). then(function(v){ console.log('Previous ' ...

Converting non www to www in React.js

I want to redirect users from http://example.com to http://www.example.com. If I'm using nginx + php, I can achieve this with the following configuration: server { listen 80; server_name example.com; return 301 http://www.example.com$req ...

Organize JSON data in Angular 6 from an observable based on a specific key

Note: While I am familiar with sorting a regular array of objects using .sort(), I am facing a challenge with an observable object that I am not accustomed to. My task involves retrieving a JSON array of objects with a service: import { Injectable } from ...

What is the process of transforming an object type into a two-dimensional array using lodash?

In order to properly display multiple tables in my Angular project, I am looking to convert an object type into an array of different objects. The object I am working with is as follows: let myObject = { internalValue:{city:"Paris", country:"France", pin ...

The CoreUI Sidebar gracefully hovers over the main page content

I recently started using CoreUI to design the layout for my application, but I ran into an issue while trying to integrate the Sidebar. Although the Sidebar is visible on the left side, I'm having trouble making sure that the router-view takes up the ...

Transform Typescript into compiled css files without using any additional tools

Currently, I am working on a monorepo project where the main project relies on another project called components. When running the entire monorepo, the main project utilizes webpack.dev while the components project simply uses the TypeScript compiler. It l ...

The shape-matching subset functionality in Typescript is experiencing issues

One of the key principles of TypeScript is that type checking focuses on the structure of values, a concept known as duck typing or structural typing. This means that only a subset of an object's fields needs to match for it to be considered compatibl ...