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

Tips for efficiently sending multiple ajax requests

Seeking help with my ajax knowledge. Currently, I have a function that is supposed to insert multiple items into an SQL database using a PHP page. However, it seems to only be inserting the last item entered. Here's the code snippet: function submitI ...

Struggling with incorporating ES6 syntax into a Node Typescript application

I encountered an error while trying to import a module Below is the code snippet: import * as express from 'express'; export class Server { app: express.Application constructor() { const port = 3000 || process.env.PORT ...

jQuery - contrasting effects of the before() and after() functions

I'm working with a sortable list that is not using jQuery UI sortable, but instead allows sorting by clicking on buttons. Sorting to the right using after() works perfectly, however, sorting to the left with before() is causing issues. First, here&ap ...

How can the border of the select element be removed when it is active in select2

After examining the CSS code, I am still unable to locate the specific property that is being applied to the main element. I am currently customizing the select2 library to suit my needs. However, I am stuck in the CSS as I cannot determine which property ...

Encountered an error while web crawling in JavaScript: Error - Connection timeout

I encountered an error while following a tutorial on web crawling using JavaScript. When I execute the script, I receive the following errors: Visiting page https://arstechnica.com/ testcrawl ...

Potential keys + keys that are present in the `initialData`

Is there a way to specify the type of data in order to include all keys that exist in initialData plus additional keys from Item as Partial(optional)? class TrackedInstance<Item extends Record<string, any>, InitialData extends Partial<Item> ...

Preventing mouse clicks on checkboxes and triggering events using JavaScript - a complete guide

We have a Table grid with multiple columns, one of which is a Select Box (CheckBox). The expected behavior is that when a row is clicked, the respective CheckBox should get checked, and clicking on the CheckBox itself should update it. I tried implementin ...

Understanding @@iterator in JavaScript: An in-depth look

Can someone shed some light on the mysterious @@iterator? It keeps popping up in tutorials but no one seems to provide a clear explanation of what it actually is. Is it a symbol literal or something else entirely? ...

Having trouble with overriding an @media query for material-ui react components?

I've been trying to modify a @media CSS rule on a Material UI component, similar to the discussions on How to over-ride an @media css for a material-ui react component and Override components like MuiTab that use media queries. However, I have not bee ...

Identifying imports from a barrel file (index.ts) using code analysis

Can anyone help me understand how the Typescript compiler works? I am trying to write a script that will parse each typescript file, search for import declarations, and if an import declaration is using a barrel-file script, it should display a message. Af ...

Is it possible to combine the existing request parameters with a new parameter in JSP/JSTL/JQuery?

Here is a sample URL: http://127.0.0.1:8080/admin/seller?email=tim%40example.com Below is a snippet of JSP code: <a class="btn btn-primary ${page==pages||pages==0?'disabled':''}" href="?page=${page + 1}">Next</a> I am ...

Upon completing the installation of Gulp, an error message stating "gulp command not found" may be displayed

Once I installed gulp.js using npm, an error message saying no command 'gulp' found popped up when trying to run the gulp command from the same directory it was installed in. Upon checking the node_modules/.bin/ directory, the gulp executable is ...

Retrieving the data from a Material UI Slider control

I'm encountering an issue with retrieving the value property I assigned to a component. event.target.value is returning undefined. How can I successfully access the value of the component? My goal is for handlePlayersChange() to be able to handle dyn ...

Can Sequelize be utilized to navigate routes?

Is there a way to access sequelize from different routes in my project? Most tutorials demonstrate how to use sequelize specifically in the app.js file, but I am wondering how to utilize it in other routes without having to initialize it each time. Is th ...

Converting a string to a date type within a dynamically generated mat-table

I am working on a mat-table that shows columns for Date, Before Time Period, and After Time Period. Here is the HTML code for it: <ng-container matColumnDef="{{ column }}" *ngFor="let column of columnsToDisplay" > ...

The event listener cannot be unbound

As a newcomer to javascript, I'm facing an issue that I couldn't find answers to despite searching extensively. Here is my problem: I have a module or class where I am attempting to create a draggable component on the screen. The objective is to ...

IE11 and how it handles Typescript and promises

Currently, I am utilizing Typescript version 2.4.2 along with Webpack for compilation purposes. Despite successful compilation, when running my code on IE11, an error 'Promise' is undefined arises. Below is a glimpse of my tsconfig: { "comp ...

What is the best way to verify multiple email addresses simultaneously?

Is there a method to validate multiple email addresses entered by users in a textarea? My current approach involves using ng-pattern for validation. ...

"eliminate" ng-if after the condition becomes true

I'm curious to know if it's possible to deactivate or remove ng-if once its value becomes true? In my project, I've constructed a tree structure using a recursive directive. Each branch in the tree has a <div ng-if="visible"> element ...

Managing users in Node.js with Express and MongoDB as the server database

Seeking the solution to implementing user management on my website. Website: Currently working with Node.js & Express, I have set up the project with Express, and the app.js file includes the following lines: app.use('/', routes); app.use(&apos ...