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?