Sharing Code in TypeScript and Project References

tl;dr

  • Strategies for sharing code and how they integrate within the TypeScript ecosystem.
  • Project References enable code sharing across multiple TypeScript projects within a single codebase (monorepo), offering modularization, dependency management, and incremental builds.
  • The simple use of Project References is straightforward but can result in cumbersome import paths like ../../../../../libs/dist/data-access/loader/common.js, which expose the project’s internal folder structure.
  • This post explores solutions to the import path issue, balancing complexity and elegance:
    • TypeScript paths aliasing adds complexity by requiring extra tooling for runtime import resolution.
    • Bundlers, while somewhat cumbersome, largely resolve these issues and provide production deployment tools.
    • npm workspaces mimic external npm dependencies using symlinks in node_modules, addressing import paths without aliasing or extra tooling and enabling package export management for better modularization.
  • In conclusion, TypeScript Project References combined with npm workspaces provide an optimal solution for multi-project code sharing within a single codebase in TypeScript.
Continue reading