The path mappings specified in the tsconfig.json file are not resolving correctly during the

Everything runs smoothly with my imports during coding, but after building the project using tsc, the imported files are not resolving to valid paths.

This is how my tsconfig.json looks:

{
  "compilerOptions": {
    "target": "ES2018" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */,
    "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,          
    "lib": ["es6"] /* Specify library files to be included in the compilation. */,
    "allowJs": true /* Allow javascript files to be compiled. */,
    "outDir": "build" /* Redirect output structure to the directory. */,
    "rootDir": "src" /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */,
    "strict": true /* Enable all strict type-checking options. */,
    "noImplicitAny": true /* Raise error on expressions and declarations with an implied 'any' type. */,
    "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
    "moduleResolution": "node",
    "resolveJsonModule": true /* Include modules imported with '.json' extension */,
    "skipLibCheck": true /* Skip type checking of declaration files. */,
    "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */,
    "allowSyntheticDefaultImports": true,
    "baseUrl": "src",
    "paths": {
      "@root/*": ["../*"],
      "@src/*": ["./*"]
    }
  }
}

The scripts section in my package.json is as follows:

  "scripts": {
    "dev": "nodemon",
    "build": "rm -rf ../build && tsc",
    "start": "yarn run build && node build/index.js",
    "lint": "eslint . --ext .ts"
  },

The use of nodemon through a json file is working well, thanks to tsconfig-paths:

{
  "watch": ["src"],
  "ext": ".ts,.js",
  "ignore": [],
  "exec": "ts-node -r tsconfig-paths/register ./src/index.ts"
}

Upon attempting to execute yarn start, an error arises in my api/build/index.js:

Error: Cannot find module '../src/app'

The code is searching for a non-existent file at ../src/app. The correct path should be ./app.

The layout of the build folder is structured as follows:

build
  routes
    index.js
    users.js
  startup
    routes.js
  app.js
  index.js

I've invested a considerable amount of time troubleshooting this issue without success. I'm uncertain about what's going wrong here.

How can I resolve this problem?

Answer №1

In order to resolve this issue, I made the decision to switch from using tsc to utilizing Babel along with babel-plugin-module-resolver for the build process of my project. This adjustment resulted in the desired outcome where everything now functions as intended. If anyone encounters a similar problem, I am prepared to share the entire .json files (specifically, please examine the build script within the package.json). Keep in mind that this code is specifically designed for deployment on a Node.js 14.x.x application, therefore adjustments will be necessary in the .babelrc file's targets section based on your target environment if you are developing for a different platform.

tsconfig.json

{
  "compilerOptions": {
    "sourceMap": true,
    "inlineSources": true,
    "target": "ES2018" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */,
    "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
    "lib": ["ESNEXT"] /* Specify library files to be included in the compilation. */,
    "allowJs": true /* Allow javascript files to be compiled. */,
    "outDir": "build" /* Redirect output structure to the directory. */,
    "rootDir": "../" /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */,
    "strict": true /* Enable all strict type-checking options. */,
    "noImplicitAny": true /* Raise error on expressions and declarations with an implied 'any' type. */,
    "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
    "moduleResolution": "node",
    "resolveJsonModule": true /* Include modules imported with '.json' extension */,
    "skipLibCheck": true /* Skip type checking of declaration files. */,
    "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */,
    "allowSyntheticDefaultImports": true,
    "baseUrl": "src",
    "paths": {
      "@root/*": ["../*"],
      "@src/*": ["./*"]
    }
  }
}

package.json

{
  "name": "api",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "dev": "nodemon",
    "typecheck": "tsc --noEmit",
    "debug": "yarn build && node --inspect --inspect-brk build/",
    "test": "jest --watchAll",
    "build": "rm -rf build/ && babel src --source-maps --extensions '.js,.ts,.tsx' --ignore '**/*.test.ts' -d build",
    "start": "export NODE_ENV=production && yarn run build && node build/index.js",
    "lint": "eslint . --ext .ts",
    "checks": "yarn lint & yarn typecheck"
  },
  "jest": {
    "testEnvironment": "node",
    "coveragePathIgnorePatterns": [
      "/node_modules/"
    ]
  },
  "dependencies": {
    "config": "^3.3.3",
    "cors": "^2.8.5",
    "express": "~4.16.1",
    "morgan": "~1.9.1",
    "node-webcam": "^0.7.0",
    "winston": "^3.3.3"
  },
  "devDependencies": {
    "@babel/cli": "^7.12.10",
    "@babel/core": "^7.12.10",
    "@babel/polyfill": "^7.12.1",
    "@babel/preset-env": "^7.12.11",
    "@babel/preset-typescript": "^7.12.7",
    "@types/config": "^0.0.37",
    "@types/cors": "^2.8.9",
    "@types/debug": "^4.1.5",
    "@types/express": "^4.17.9",
    "@types/morgan": "^1.9.2",
    "@types/node": "^14.14.14",
    "@types/supertest": "^2.0.10",
    "@typescript-eslint/eslint-plugin": "^4.10.0",
    "@typescript-eslint/parser": "^4.10.0",
    "babel-plugin-module-resolver": "^4.1.0",
    "eslint": "^7.16.0",
    "jest": "^26.6.3",
    "nodemon": "^2.0.6",
    "supertest": "^6.0.1",
    "ts-node": "^9.1.1",
    "tsconfig-paths": "^3.9.0",
    "typescript": "^4.1.3"
  }
}

.babelrc

{
  "presets": [
    "@babel/preset-typescript",
    [
      "@babel/preset-env",
      {
        "targets": { "node": 14 }
      }
    ]
  ],
  "plugins": [
    [
      "module-resolver",
      {
        "root": "./src",
        "alias": {
          "@root": ["./"],
          "@src": ["./src"]
        },
        "extensions": [".js", ".ts"]
      }
    ],
  ],
  "sourceMaps": true
}

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

Automatically numbering text boxes upon pressing the enter key

Is there a way to automatically number textboxes when I type "1" and hit enter in one of them? For example, if I have 3 textboxes and I type "1" in the first one, can the other textboxes be numbered as 2 and 3 accordingly? <input type="text&qu ...

angular: handling duplicates in ng-repeat

Here is the JSON data: streams = [{ id: 0, codec_type: 'video', content: '1920x1040 - H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10' }, { id: 1, codec_type: 'audio', content: '5.1(side) - cze - undefined' }, ...

I'm curious why my background generator is only altering a portion of the background instead of the entire thing

I've been attempting to create a JavaScript random background changer, but I'm encountering some challenges. The main issue is that instead of changing the entire page's background, it only alters a strip of it. Additionally, I'm curiou ...

Spin a Material UI LinearProgress

I'm attempting to create a graph chart using Material UI with the LinearProgress component and adding some custom styling. My goal is to rotate it by 90deg. const BorderLinearProgressBottom = withStyles((theme) => ({ root: { height: 50, b ...

Encountering an undefined property error while using Array.filter in Angular 2

hello everyone, I am currently faced with an issue while working on a project that involves filtering JSON data. When using the developer tools in Chrome, it keeps showing me an error related to undefined property. chart: JsonChart[] = []; charts: JsonC ...

Oh no! There seems to be an unexpected token "<" in my React Native project on Visual Studio Code

When utilizing react-native in VS Code, I encounter an issue where my code fails to compile and throws a syntax error for the "<" symbol. Strangely, many tags work fine with "react-native run-android" from the Terminal. This is the code snippet that I ...

the behavior subject remains static and does not update

Working on setting my language in the BehaviorSubject with a default value using a LanguageService. The service structure is as follows import {Injectable} from '@angular/core'; import * as globals from '../../../environments/globals'; ...

Adjusting the minimum value on a textfield with JQuery Validate plugin in real-time

I am attempting to dynamically update the minimum value on one field based on input from other fields. Here is a brief overview of my code: $("#new_project").on("click", function() { switch($('input:radio[name=quality-level]:checked').val() ...

Learn the process of extracting a particular value from JSON data and displaying it in HTML by utilizing AngularJS's ng-repeat directive

As a newcomer to angularjs, I am encountering difficulties retrieving and displaying a specific value from a json file in order to showcase it on my view page using angularjs ng-repeat for image source. My goal is to repeat the json file based on a particu ...

Displaying data-table with only the values that are considered true

Right now, I am utilizing the AgReact table to exhibit data fetched from my endpoints. The data-table is functioning properly, however, it seems to be unable to display false values received from the endpoints on the table. Below are the snippets of my cod ...

The request to localhost resulted in a 404 error, indicating that the resource was not found

When attempting a file upload operation using MV.Net, I encountered the GET http://localhost:55298/Home/test2.json 404 (Not Found) error while trying to upload a file. How can this issue be resolved? <input type="file" name="file" ...

The ideal version of firebase for showing messages in the foreground

Looking to instantly display notifications as soon as they are received? I recently watched a video on Angular 8 + Firebase where version 7.6.0 was discussed. While the notification is displayed in the foreground for me, I find that I need to click on some ...

Tips for determining if an item in one array is present in a different array

Looking for a way to disable a button using React code? Take a look at the snippet below: todos.filter(todo => todo.completed === true) .map(todo => todo.id) .includes(this.state.checkedIds) But there's a catch - it always seems to return ...

How can I add color to arrow icons in tabulator group rows?

Is there a way to specify the color of the arrows in collapsed/expanded group rows? Also, what CSS code should I use to define the font color for column group summaries? You can view an example of what I am trying to customize here: https://jsfiddle.net/s ...

Sending an HTTP request from within an Express/Node.js application

I am currently in the process of setting up an express service for a program I am developing. The goal is to interact with an external API, retrieve the data, and store it in a MongoDB database that I have already set up. While this task may seem straight ...

Add a fresh widget to the DOJO attachment point without overwriting

Here is some code I have: postCreate: function() { this.items.forEach(lang.hitch(this, function(item) { new SideNavigationItem({ name: item.name }, this.container); })); } This code snippet ...

How to change the background color of a slider using jQuery

As a newcomer to web programming, I am currently working on incorporating a slider into my website using jQuery. My goal is to change the background color of the slider to red when the value is less than 5 and green when it exceeds 5. Can this be achieved ...

Transferring data from JavaScript to PHP with the help of AJAX

I am encountering issues with my code, as I cannot seem to successfully send coordinates from JavaScript to PHP using AJAX. Although I can retrieve values from JavaScript into a textbox, the values are not being transferred to PHP. Any assistance on resolv ...

Using Google Script Code in Sheet to input a key and click on the submission button

Is there a way to enable using the Enter key in addition to clicking the submit button to input data and save it to a cell? I'm having trouble getting my current code to work. Any suggestions on how to modify it? <script> var itemBox = document ...

Implementing the jQuery datepicker in Angular.js can be challenging

I recently started learning Angular.js and have been working on a web application using this framework. I am now looking to include a datepicker in one of my forms. Below is the code snippet that I have implemented: app.js myapp.directive(& ...