Explicit dependencies
Organize application code into files with explicit imports and exports.
TypeScript · Const
A TypeScript file with a top-level import or export is a module; a file without either is a script. Modules have their own scope, while scripts contribute declarations to the global scope.
TypeScript treats a file with a top-level import or export as a module. That file has its own scope, so its declarations are not placed in the global scope; files without top-level imports or exports are scripts instead.
import { name } from "module";
export { name };import or export is enough to classify the file as a module.export const answer = 42;
import { answer } from "./answer.js";
console.log(answer);A file with a top-level export is a module, and another module can import its exported binding.
Organize application code into files with explicit imports and exports.
Prevent unrelated files from sharing names through the global scope.
Expose only selected APIs from an implementation file.
A TypeScript file is a module when it contains a top-level import or export. Otherwise, TypeScript treats it as a script, whose contents are available in the global scope.
Follow-up: How do you make a file a module when it has no runtime imports or exports? Add an explicit type-only import or export, such as export {}.
Module scope prevents declarations from being shared through the global scope. Files can expose selected bindings through exports and consume them through imports.
Follow-up: What is the practical benefit in a large codebase? Explicit dependency boundaries reduce accidental name collisions and make relationships easier for tooling to analyze.
The module concept follows ECMAScript 2015: top-level import and export determine module status. This is separate from the particular runtime module format used when JavaScript is emitted.
Follow-up: Which compiler setting addresses emitted format? The module compiler option controls the module format of emitted JavaScript and also informs related module analysis.
importexportscriptmoduleNamespaces and Modules