In a typescript project, imagine the following organizational structure:
| package.json
| tsconfig.json
|
\---src
| app.ts
|
\---foobar
Foo.ts
Bar.ts
The tsconfig.json
file is set up to have ./src/
as the baseUrl
.
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"noImplicitAny": true,
"removeComments": true,
"preserveConstEnums": true,
"outDir": "./dist/",
"baseUrl": "./src/"
},
"include": [
"./src/**/*"
],
"exclude": [
"node_modules"
]
}
If we wish to import Foo
into Bar.ts
, setting the baseUrl
allows us to use absolute paths for importing modules.
import { Foo } from 'foobar/Foo'
Instead of using relative paths like this:
import { Foo } from './Foo'
Based on my understanding, the TypeScript compiler should be able to resolve foobar/Foo
to ./Foo
automatically during compilation of Bar.ts
.
import { Foo } from 'foobar/Foo';
export class Bar {
foo: Foo;
constructor(num: number) {
this.foo = new Foo(num);
}
}
Although running tsc
compiles without errors, inspecting the compiled Bar.js
reveals that the path resolution has not been done accurately, resulting in a Cannot find module error if executed.
"use strict";
const Foo_1 = require("foobar/Foo");
class Bar {
constructor(num) {
this.foo = new Foo_1.Foo(num);
}
}
exports.Bar = Bar;
Hence, the question arises: How can I ensure that tsc
accurately resolves absolute paths when importing modules with baseUrl
? And if this functionality is unattainable, what is the purpose of baseUrl
exactly?