A
A
Artem2018-05-03 19:24:51
Angular
Artem, 2018-05-03 19:24:51

How to import a module relative to the project root in typescript?

/app
|--/src
|  |--currentfile.ts
|  |--anotherfile.ts
|
|--/env
   |--environment.ts

currentfile.ts
import { another } from './anotherfile';
import { environment } from 'env/environment';

How can I configure tsconfig.js so that such module imports work? There are no problems with importing relative to the current location, i.e. anotherfile is imported successfully. But when I try to import from the root of the project, namely the file env/environment , webpack swears that the module was not found in /app/src
baseUrl: '.' installed
UPD.
I also noticed that the problem occurs when importing the Injectable class. I don't understand how this affects imports relative to the project root.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem, 2018-05-04
@Cruper

The problem was solved in the following way.
Perhaps somewhere inattentively read the documentation.
In tsconfig.ts write:

{
  "compilerOptions": {
    "baseUrl": ".", // корень проекта, в данном случае директория, где лежит конфиг
    "paths": [
       "env/*": ["env/*"]
    ]
  }
}

Root-relative imports work if the baseUrl and paths properties are present in tsconfig.json . Namely, if you specify an import without the above properties in the config, the webpack will search for the env/environment module relative to the file where this import was made. To import relative to the project root in the config, you need to write
{
  "compilerOptions": {
    "baseUrl": ".", // корень проекта, в данном случае директория, где лежит конфиг
    "paths": [
       "env/*": ["env/*"]
    ]
  }
}

Thus, when encountering an import starting with env/ , webpack will look for the module relative to baseUrl

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question