Tsconfig References in TypeScript

Rana Hasnain Khan Jul 29, 2022
Tsconfig References in TypeScript

We will introduce tsconfig references in TypeScript.

the tsconfig References in TypeScript

The tsconfig file allows us to define the different parts of the application as separate TypeScript modules. This file allows us to configure each module differently and build them according to our application’s needs.

There are some main changes introduced in TypeScript 3.0. The tsconfig.json file has been renamed to tsconfig-base.json.

This makes the root folder not be considered a TypeScript project because TypeScript requires tsconfig.json to be present to consider the directory as a TypeScript project.

The present project structure is as shown below.

tsproject/
    src/
        entity.ts # exports an entity
        tsconfig.json
    test/
        entity.spec.ts # imports an entity
        tsconfig.json
    tsconfig-base.json

As we can see from the above example that both src and test now contain tsconfig.json files inside them; because of this, they will be considered separate projects. But if we look into the contents of both files, they are similar.

At the same time, all the configurations are stored in the tsconfig-base.json file, which is then inherited by both tsconfig.json files.

Now, we should be wondering how src and test folders are linked to make things work and how a relationship is made between these folders. In the TypeScript 3.0 version, both folders are referenced from the outside by declaring them as composite.

The contents from the src and test configuration files are shown below.

// src configuration in /src/tsconfig.json
{
    "extends": "../tsconfig-base.json",
    "compilerOptions": {
        // compiler options
        "composite": true
    }
}
// test configuration in /test/tsconfig.json
{
    "extends": "../tsconfig-base.json",
        "references": [
        { "path": "../src" }
    ]
}

Now, let’s discuss how we can run tests. Before running tests, we must ensure that we have built the src.

We can easily build it by using the following command in the console, as shown below.

tsc --build src
Rana Hasnain Khan avatar Rana Hasnain Khan avatar

Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.

LinkedIn