Slava Fomin II
Slava Fomin II

Reputation: 28611

Set TypeScript compiler's base/working directory

It looks like TypeScript compiler resolves files relative to the location of the tsconfig.json file.

Is there a way to specify an alternative base directory, which will be used for relative paths resolution?

I want to use a generic tsconfig.json file to compile multiple projects in various directories.

Here's the related question in TypeScript official repository.

Upvotes: 5

Views: 1890

Answers (1)

Ewald Benes
Ewald Benes

Reputation: 632

I've got a similar problem as you but solved it with tsconfig.json in each project.

I have frontend and backend code and shared code between the two. It has the following directory structure.

/my-project
   /common
      *.ts
   /frontend
      *.ts
      tsconfig.json
   /backend
      /src
         *.ts
      tsconfig.json

Here's the backend/tsconfig.json:

...
"compilerOptions": {
  ...
  "outDir": "./dist",
  ...
}
...

Typescript compiler automatically determines the greatest common ancestor directory, hence rootDir, of all *.ts files according to your tsconfig.json. You don't even need to specify rootDir explicitly because the compiler walks the hierarchy up to my-project and sets it as the root.

The import inside a backend/some.ts looks like:

import { Foo } from '../../common/some-shared';

Because of the automatic rootDir calculation of the compiler the only gotcha is that the output inside the backend/dist directory looks like this:

/dist
    /common
       *.js
    /backend
       /src
          *.js

I haven't figured out yet how I can get rid of the ugly dist/backend/src structure without using any copying or bundling with Webpack, etc prior to compilation. From what I searched it's (still) not possible to do that with the Typescript compiler only. Maybe someone has hints... Hope that helped for now.

Upvotes: 3

Related Questions