How to get tsc to resolve absolute paths when importing modules using baseUrl?

Consider a simple typescript project with the following directory structure:

| package.json | tsconfig.json | \---src | app.ts | \---foobar Foo.ts Bar.ts 

tsconfig.json was configured so that ./src/ was baseUrl .

 { "compilerOptions": { "module": "commonjs", "target": "es6", "noImplicitAny": true, "removeComments": true, "preserveConstEnums": true, "outDir": "./dist/", "baseUrl": "./src/" }, "include": [ "./src/**/*" ], "exclude": [ "node_modules" ] } 

Now suppose we want to import Foo into Bar.ts I understand that by setting baseUrl , now we can use absolute paths to import modules

 import { Foo } from 'foobar/Foo' 

unlike relative paths

 import { Foo } from './Foo' 

If my understanding is correct, the typescript compiler should be able to automatically resolve foobar/Foo to ./Foo when compiling Bar.ts

 import { Foo } from 'foobar/Foo'; export class Bar { foo: Foo; constructor(num: number) { this.foo = new Foo(num); } } 

Running tsc compiles without errors. However, when we really look at the compiled Bar.js , we will see that the path was not resolved correctly, which will give us the Can not find module error if we run it.

 "use strict"; const Foo_1 = require("foobar/Foo"); class Bar { constructor(num) { this.foo = new Foo_1.Foo(num); } } exports.Bar = Bar; 

So my question is: how can I get tsc to correctly resolve absolute paths when importing modules using baseUrl ? Or if this is not something that can be done, what is the purpose of baseUrl , then?

+6
source share
1 answer

The problem is that your module loader does not know how to find the module given the absolute path of foobar/Foo .

The TypeScript compiler (tsc) resolves the module paths correctly, otherwise you will get compilation errors. But you need to properly configure the bootloader of your module.

For example, from the documentation for RequireJS :

Supported configuration options:

baseUrl: The root path for all module searches.

The TypeScript documentation says a little about why you might need baseUrl :

Using baseUrl is common practice in applications that use AMD module loaders, where the modules are "deployed" to the same folder at runtime. The sources of these modules can live in different directories, but the script assembly combines them.

+1
source

Source: https://habr.com/ru/post/1015129/


All Articles