TypeScript is unable to locate the module using a non-relative path of 'src/xxx'

I am facing an issue with resolving non-relative modules in TypeScript. I have tried using baseUrl, paths, and other methods, but none seem to work...

tsconfig.json

{
  "compilerOptions": {
    "allowJs": true,
    "baseUrl": ".",
    "esModuleInterop": true,
    "module": "commonjs",
    "sourceMap": true,
    "strict": true,
    "target": "esnext",
    "typeRoots": ["node_modules/@types"]
 }
}

Directory structure of the project:

root
  ├─src
    ├── APIs
    ├── config
    ├── constants
    ├── middlewares
    ├── models
    ├── routes
    ├── services
          - foo.ts   
    ├── utils
    └── app.ts

In app.ts

import foo from 'src/services/foo'

When running with ts-node src/app.ts, I encounter the following error:

Cannot find module 'src/services/foo'

Answer №1

At last, I included the paths option to resolve the issue.

tsconfig.json

{
  "compilerOptions": {
    "baseUrl": ".",
    "esModuleInterop": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "removeComments": true,
    "sourceMap": true,
    "target": "esnext",
    "strict": true,
    "noUnusedLocals": true,
    "paths": {
      "@/*": ["src/*"]
    },
    "typeRoots": ["./src/@types", "./node_modules/@types"]
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "**/node_modules/*", "**/*.spec.ts"]
}

In app.ts:

import foo from '@/services/foo'

Answer №2

To implement path aliases in your project, you will need to include tsconfig-paths and module-alias in your package.json as shown below:

    "_moduleDirectories:" ["src"]

In your app.ts file, add the following line:

    import 'module-alias/register';

Additionally, create a file named tsconfig-path.js in the root directory with the following content:

const tsConfigPaths = require('tsconfig-paths');
const tsConfig = require('./tsconfig.json');
tsConfigPaths.register({
    baseUrl: tsConfig.compilerOptions.outDir,
    paths: tsConfig.compilerOptions.paths,
});

Don't forget to update your tsconfig.json file as follows:

{
    "compilerOptions": {
        "baseUrl": "src",
        "paths": {
            "*":["./*"]
        }
    },
    "exclude": ["node_modules"],
    "include": ["./src/**/*.ts"]
}

Answer №3

To enable path mapping in TypeScript, you must first install the tsconfig-paths package and then include the following code snippet in your tsconfig.json file:

"ts-node": {
    // Don't forget to run `npm i -D tsconfig-paths` after adding this
    "require": ["tsconfig-paths/register"]
  }

More information can be found here: https://github.com/TypeStrong/ts-node#paths-and-baseurl

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

Redirecting with response headers in Next.js

Objective: The Goal: Clicking a button on a page should send a request to the controller. The controller will then set a cookie, and upon receiving the response, redirect the page to another page, such as the about page. Directly Calling API route from th ...

What is the most effective method for creating Typescript type predicates that yield the most specific types when filtering arrays?

I believed I had discovered the perfect method for defining predicates: declare function isNumber<T>(x: T): x is Extract<T, number>; declare function isFunction<T>(x: T): x is Extract<T, Function>; ... and so forth This technique l ...

Presenting a Dialogue Box Message

Currently, I am a beginner in Angular and I am working on developing a web page. My goal is to have a dialog button that, when clicked, displays the heading message from the dialogComponent. However, when I click the button, the dialog box appears but it d ...

A TypeScript interface or class

Just had a lively discussion with a coworker and wanted to get some clarification. When shaping an object in TS, should we use a class or an interface? If I need to ensure that a function returns an object of a specific type, which one is the best choice? ...

What is the best approach to repurpose a jest test for various implementations of a shared interface?

I'm facing a challenge: describe("Given a config repository", () => { let target: ConfigRepository; beforeEach(() => { target = InMemoryConfigRepository(); }); test("When creating a new config, Then it is ...

Issue with Angular2 - namespace webdriver not detected during npm installation

Upon restarting my Angular2 project, I ran the npm install command and encountered this error message: node_modules/protractor/built/browser.d.ts(258,37): error TS2503: Cannot find namespace 'webdriver' Does anyone have insight into the origin ...

Examining the array to ensure the object exists before making any updates in the redux

Is there a way to determine if an object exists in an array and update it accordingly? I attempted to use the find method, but it couldn't locate the specified object. I also tried includes, but it seems to be unable to recognize the item within the ...

Why isn't tslint:disable working? What could be causing this issue?

Despite setting tslint:disable, I am still receiving tslint warnings. The specific warnings that are appearing include: [ts] Argument of type 'string' is not assignable to parameter of type 'RequestInit | undefined'. (parameter) optio ...

Service error: The function of "method" is not valid

In one of my Angular 2 applications, I have a class that contains numerous methods for managing authentication. One particular method is responsible for handling errors thrown by the angular/http module. For example, if a response returns a status code o ...

Transform the fetch request to utilize oboe for parsing JSON streams in a Typescript environment

I've been working on this fetch call: api<T>(url: string, headers: Request): Promise<T> { return fetch(url, headers) .then(response => { if (!response.ok) { throw new Error(respo ...

When conditionals are used, Typescript struggles to accurately infer the correct type

When using the same type (Options<ST extends SwitchType) for useStrategy options parameter and for toPayload options, I expected Typescript to infer the correct type for toPayload options. However, I encountered an error message: The argument of type ...

Having trouble resolving the signature of a class decorator when invoked as an expression with @Injectable in Angular

Error Message: Unable to resolve the signature of a class decorator when called as an expression. The argument type 'ClassDecoratorContext' is not compatible with the parameter type 'string | symbol | undefined'. After creating a book ...

What is the significance of incorporating 'Actions' as data within the Redux framework?

According to Redux documentation, creating actions and action creators is necessary. Here's an example: function addTodo(filter) { return { type: SET_VISIBILITY_FILTER, filter } } Next step is to write reducers, like this: function t ...

The type 'string | null' cannot be assigned to the type 'string | undefined'. Specifically, the type 'null' cannot be assigned to the type 'string | undefined'

When I define a property as id!:string; or id:string=''; and try to assign the value of params, an error occurs (property) MoreParametersComponent.id: string ts(2322)Type 'string | null' is not assignable to type 'string'. Ty ...

How to Measure the Length of an Undefined Value in Jasmine Angular Unit Tests

Here's a function that I have: updateParts(enviromentContainsAllParts: PartsContainsAllParts): Observable<boolean> { const enviroment = cloneDeep(this.enviroment); enviroment.containsAllPart = enviromentContainsAllParts.containsAllPart ...

TypeScript raises concerns when a function returns a boolean instead of an object

I have a function called createFields structured like this: The map function being used here is from the lodash library. const createFields = (usecase: SchemaObject): FieldInterface[] => { // TODO: Make the form blueprint to be generated from JSON s ...

Angular is failing to detect a change in the initial element of an array

In my Angular app, I am working on displaying a list of dates for the current week. Users should be able to view previous weeks by clicking a button, so I am using an Observable to update the array of dates and trying to display the updated array. Althoug ...

What can TypeScript do with high-level type functions?

Take a look at the following pseudo-code attempting to define a higher-order type function with a function-typed parameter M<?>: type HigherOrderTypeFn<T, M<?>> = T extends (...) ? M<T> : never; The syntax M<?> is not va ...

TypeScript Error: The Object prototype must be an Object or null, it cannot be undefined

Just recently, I delved into TypeScript and attempted to convert a JavaScript code to TypeScript while incorporating more object-oriented features. However, I encountered an issue when trying to execute it with cmd using the ns-node command. private usern ...

Exploring the inner workings of Angular v4.4 and gaining insight into the roles of platformBrowserDynamic and PlatformRef

Recently, I have come into possession of an Angular 4.4 application that utilizes Webpack v3.5 and TypeScript v2.3.3. Struggling to decipher the imported code, I am at a loss understanding its functionality and correctness. To simplify matters for analysis ...