“This is the fourth day of my participation in the August More Text Challenge. For details, see: August More Text Challenge.”

Use the module

Modules include code and declarations

Modules can provide better code reuse, code isolation, and better support for packaging tools. For Node applications, modules are preferred over namespaces. Since ES6, JS has had a module system and has been implemented by a compiler.

Using namespaces

Namespaces are TS specific ways of organizing code. Namespaces are essentially multiple simple JS objects. So it’s easy to use namespaces. The same namespace can be spread across multiple files and concatenated by –outFile. In Web applications, namespaces are a great way to organize code. The generated dependency file can be used

However, in a large application, namespaces make it difficult to distinguish the dependencies of the various components of the project.

A module behaves differently from a namespace

Use /// in modules

Error behavior: Use /// syntax to import a module. Modules can only be imported using the import syntax.

However, if it is a non-module file, such as a pure declaration file, it can be imported using the /// syntax.

someModule.ts

Declare Module" someModule"{export function (): string; }Copy the code

index.ts

/// <reference path="someModule.ts">
import * as m from "SomeModule";
Copy the code

At this point, /// is used to locate the living file.

Unnecessary namespaces

Shapes: shapes: shapes: shapes: shapes: shapes: shapes: shapes: shapes: shapes

shape.ts

export namespace Shapes {  export class Triangle {    /* ... */  }  export class Square {    /* ... */  }}
Copy the code

shapeConsumer.ts

import * as shapes from "./shapes"; let t = new shapes.Shapes.Triangle(); // shapes.Shapes?Copy the code

In TS, one of the characteristics of a module is that the consumer of the module gives it a name when it is used. Therefore, there is no need to wrap another namespace around the exported object.

And the use of namespaces generally provides a local logical block of code to prevent naming conflicts. The module file itself is a large block of code whose top-level name is defined by the module consumer, so there is no need to wrap a namespace around the module.

So the code can be modified as follows:

shape.ts

export class Triangle {    /* ... */  }  
export class Square {    /* ... */  }
Copy the code

index.ts

import * as shapes from "./shapes"; let t = new shapes.Triangle();Copy the code