๐ŸŽ“ A1Learner
๐Ÿ”
0 of 37 lessons completed

TypeScript Project References

Project references split a codebase into smaller projects that build in dependency order. Each referenced project is composite, so it emits declarations that dependent projects compile against.

A composite library tsconfig

The library config turns on composite and declaration output. Those two settings let other projects build against this one.

{
  "compilerOptions": {
    "target": "es2020",
    "module": "commonjs",
    "strict": true,
    "composite": true,
    "declaration": true,
    "outDir": "out"
  },
  "include": ["src"]
}

An app tsconfig with references

The app config names the library project in its references. The build tool reads this entry to order the build.

{
  "compilerOptions": {
    "target": "es2020",
    "module": "commonjs",
    "strict": true,
    "outDir": "out"
  },
  "references": [{ "path": "../lib" }]
}

The lib.d.ts file

This declaration file stands in for the output tsc -b writes when it builds the library project. The app compiles against these declarations.

export declare function greet(userName: string): string;
export declare const version: string;

The lib.js file

This JavaScript file stands in for the library build output beside the declarations. It holds the code that runs.

export function greet(userName = "friend") {
  return "Hello, " + userName + "!";
}

export const version = "2.0.0";

Example

import { greet, version } from './lib';

console.log(greet('Ada'));
console.log('Library version: ' + version);

Key points

  • A composite project emits declaration files beside its JavaScript output.
  • A references entry in a tsconfig names a project that must build first.
  • The command tsc -b builds referenced projects before the projects that depend on them.
  • A dependent project reads the referenced project through its emitted declaration files.

In this example, the app imports the library by its base name, the declaration file supplies the types, and the JavaScript file supplies the running code, exactly as a built reference would.

Note

Editing a referenced project means rebuilding it before dependents see the change.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท TypeScript Playground

Exercise

What does tsc -b do with project references?