“This is the 19th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021”

preface

In the previous article, we explained how to use namespaces in TS to organize your code in the following format: namespace X {}; And we solved a legacy problem: when a single file is too large, it is split into different files based on requirements; Finally, use the form import q = X.Y.Z to simplify the namespace

Related portals:

  • How do you use namespaces in TS to organize your code
  • TS separates a single file into different files
  • Let’s look at ways to simplify namespace manipulation in TS

This article describes common namespaces and module pitfalls and how to avoid them

The body of the

Before I talk about avoiding the pitfalls of namespaces and modules in TS, let me briefly explain the namespaces and modules here

To borrow a line from a previous article:

In keeping with ECMAScript 2015 terminology, starting with TypeScript 1.5, “external modules” are called “modules” and “internal modules” are called “namespaces.”

Here are two common mistakes

Use with modules/// <reference>

A common mistake is to use ///

to reference a module file. Import should be used instead

To understand the difference, we need to know how the compiler locates module type information based on the import path

Here’s what the official said:

The compiler first tries to find.ts,.tsx, or.d.ts in the corresponding path. If none of these files are found, the compiler looks for external module declarations.

Such as:

  • myModules.d.tsIn the file
// In a .d.ts file or .ts file that is not a module:
declare module "SomeModule" {
    export function fn() :string;
}
Copy the code

Then reference labels in other module files specify the location of foreign modules

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

Unnecessary namespaces

In TS, different modules never use the same name in the same scope. Because the people who use modules name them, there is no need to wrap exported symbols in a namespace

Namespaces are used to provide logical grouping and avoid naming conflicts, and should not be used for modules

END

That’s all for this article. If you have any questions, please point out