Capítulo 24 de 36
Modules and namespaces are two distinct code-organization mechanisms with different trade-offs — modern TypeScript recommends ES Modules by default, and this chapter is mainly a pitfalls guide for people migrating from or mixing the two.
outFile, historically useful for <script>-tag-based web apps without a bundler, but they pollute the global namespace and make dependencies between files harder to see as an app grows./// <reference>-ing a module is a common mistake: the triple-slash reference directive is for pulling in ambient declaration files (.d.ts files with declare module "Name" {...}), not for referencing another module's implementation file — that's what import is for. The compiler resolves an import path by looking for .ts/.tsx/.d.ts files matching the path, and only falls back to an ambient module declaration if no real file is found; the reference tag exists to make sure that ambient declaration file is loaded into the program at all (this is how consumers of node.d.ts typically pull it in).export namespace Shapes { export class Triangle {} }) is redundant and confusing — a module is already its own scope, and the consumer decides what local name to bind the whole import to (import * as shapes from "./shapes"). Adding an inner namespace just forces an awkward extra .Shapes. hop (shapes.Shapes.Triangle) for no isolation benefit modules don't already provide on their own.Triangle without conflict, because each consumer imports and names them independently.outFile (bundling multiple sources into one output) is only possible when targeting module: "amd" or module: "system", not commonjs/umd, since those formats don't support concatenating multiple modules into a single file the way AMD/SystemJS do.// shapes.ts — don't do this:
export namespace Shapes {
export class Triangle {}
}
// consumer: shapes.Shapes.Triangle — redundant extra hop
// shapes.ts — do this instead:
export class Triangle {}
// consumer: import * as shapes from "./shapes"; new shapes.Triangle()
import, not /// <reference>, to pull in another module's real implementation — reference tags are for ambient .d.ts declaration files only.outFile bundling is gated by module target — it doesn't work with commonjs/umd.declare module "x" {...}) referenced in the /// <reference> pitfall.