Search code examples
typescriptcompiler-constructiontranspiler

TypeScript module-resolution and code-generation phases


I'm trying to understand the process of the module resolution in TypeScript.

Assume I have two files. A.ts and B.ts, and "A" imports "B".
How the module resolution works? and when ? (in the compiler phase).

After parsing each of the files, and building two ASTs. what's the next phase of the compiler?
How does it know to resolve the variables (or types) from file "B" in file "A"?
I have two assumptions:
1. it looks at the symbol table of file "B", and do the type-checking.
2. merging the ASTs into one tree? (of the whole program)

According to these assumptions, I'm also interesting to know how the code-generation affected by that.
1. If the first assumption is correct, the code-generation is more complicated. because you need to generate the JS code based on the ordering of the dependencies. (how does it detect import cycles? if A import B and vise versa).
2. If the second assumption is correct, it feels to me that the code-generation will be more easy to do. but I'm assuming that it will need to do for it a "topological sort" for the modules, before generating the code.

Thanks in advance.


Solution

  • TypeScript doesn't merge files together; it generates import statements, require calls, or define calls depending on the value of your tsconfig's "module" configuration. (look at --module on this page of the handbook) For this reason, TypeScript never needs to worry about circular dependencies or merge ASTs.

    In your example specifically, "A.ts" is compiled into "A.js" and "B.ts" is compiled into "B.js".

    Also, TypeScript's code generation doesn't use or need type information. Because of this:

    • There can be hundreds of type errors and the code will still compile identically to if the type errors were eliminated
    • You can compile plain JavaScript code, for example, downleveling ES2015 to ES3.

    The only exception is const enums since the enumerated values are inlined into the code whenever referenced. However, since the values are inlined, module ordering is not an issue.