JavaScript Development Space

How to Use References in TypeScript

What Are References in TypeScript?

Introduced in TypeScript 3.0, References allow developers to split large codebases into smaller, independent components. This modular approach improves build times, ensures clear separation of concerns, and simplifies project management. Paired with the --build flag, References enable incremental builds for enhanced performance.

Key Benefits of References

1. Improved Build Efficiency:

References work with --build to enable incremental builds, reducing unnecessary recompilation.

2. Better Code Organization:

Projects can be divided into logical components, making them easier to maintain and scale.

3. Clear Dependency Management:

References specify dependencies explicitly, ensuring components compile in the correct order.

How References Work

References are defined in the root tsconfig.json file using the references field. For example:

json
1 {
2 "files": [],
3 "references": [
4 { "path": "./tsconfig.app.json" },
5 { "path": "./tsconfig.node.json" }
6 ]
7 }
  • tsconfig.app.json: Configuration for frontend applications (e.g., Vue 3).
  • tsconfig.node.json: Configuration for backend or Node.js environments.

Each referenced file merges its settings into the main configuration, ensuring a seamless build process.

Why Use Multiple Configuration Files?

Environment-Specific Settings:

  • Frontend uses ESModules, while backend may rely on CommonJS.
  • Different tools (e.g., Vite vs. Node.js) require tailored configurations.

Improved Flexibility:

  • Separate configurations for development and production environments enhance maintainability.

Example: Project with References

Project Structure

bash
1 /my-project
2 /module-a
3 tsconfig.json
4 index.ts
5 /module-b
6 tsconfig.json
7 index.ts
8 tsconfig.json

Root tsconfig.json

json
1 {
2 "files": [],
3 "references": [
4 { "path": "./module-a" },
5 { "path": "./module-b" }
6 ]
7 }

Module-A Configuration

json
1 // module-a/tsconfig.json
2 {
3 "extends": "../tsconfig.base.json",
4 "compilerOptions": {
5 "outDir": "../dist/module-a",
6 "rootDir": "."
7 },
8 "include": ["index.ts"]
9 }

Module-B Configuration

json
1 // module-b/tsconfig.json
2 {
3 "extends": "../tsconfig.base.json",
4 "compilerOptions": {
5 "outDir": "../dist/module-b",
6 "rootDir": "."
7 },
8 "include": ["index.ts"],
9 "references": [
10 { "path": "../module-a" }
11 ]
12 }

Incremental Compilation with --build

Run the following command for an optimized build process:

tsc --build

To check the build order and skipped files:

tsc -b --verbose

Conclusion

References and --build are essential tools for managing large TypeScript projects. By splitting codebases into smaller components, developers can improve build performance, ensure modularity, and maintain environment-specific configurations effortlessly.

JavaScript Development Space

© 2025 JavaScript Development Space - Master JS and NodeJS. All rights reserved.