Namespaces and modules

Keywords: Javascript JQuery TypeScript

introduce

A module is executed in its own scope, not in the global scope, which means that variables, functions, classes, etc. defined in a module can only be used after the module is introduced

Export declarations: Any declaration can be exported by adding the export keyword (for example, variables, functions, classes, type aliases, or interfaces)

Default export: Each module can be exported using the default module, and there can only be one default export
Class and function declarations can be marked directly as default exports, and the names of classes and functions marked as default exports can be omitted

// default export
let JQuery = 'jquery';
declare let $: JQuery;
export default $;
import $ from 'jquery';

export = and import = require()

To support exports for CommonJS and AMD, TypeScript provides export =syntax
Export = The syntax defines the export object of a module, where the object refers to a class, interface, namespace, function, or enumeration

Note: If you export a module using export =, you must import the module using the specific syntax import module = require("module") of TypeScript

let numberRegexps = /^[0-9]+$/;
class ZipCodeValidator {
    isAcceptable(s: string) {
        return s.length === 5 && numberRegexps.test(s);
    }
}
export = ZipCodeValidator;
// test
import zip = require("./ZipCodeValidator");
let strings = ["Hello", "98052", "101"];
let validator = new zip();
strings.forEach(s => {
  console.log(`"${ s }" - ${ validator.isAcceptable(s) ? "matches" : "does not match" }`);
});

Namespace

After TS1.5, internal modules are called namespaces and external modules are simply modules

Declaration: Any place where a module is declared using the module keyword should be replaced with the namespace keyword to avoid confusing new users with similar names

Background: As more validators are added, a means of organizing code is needed to record their types without worrying about naming conflicts with other objects, so validators need to be wrapped in a namespace instead of in a global namespace

interface StringValidator {
  isAcceptable(s: string): boolean;
}
let lettersRegexp = /^[A-Za-z]+$/;
let numberRegexp = /^[0-9]+$/;
class LettersOnlyValidator implements StringValidator {
  isAcceptable(s: string){
    return lettersRegexp.test(s);
  }
}
class ZipStrValidator implements StringValidator {
  isAcceptable(s: string){
    return s.length === 5 && numberRegexp.test(s);
  }
}
let strings = ["Hello", "98052", "101"];
let validators: {[s: string]: StringValidator;} = {};
validators['ZIP code'] = new ZipStrValidator();
validators['Letters only'] = new LettersOnlyValidator();

for(let s of strings){
  for(let name in validators){
    let isMatch = validators[name].isAcceptable(s);
    console.log(`'${ s }' ${ isMatch ? "matches" : "does not match" } '${ name }'.`);
  }
}
// Validator using namespace
namespace Validation {
  export interface StringValidator {
    isAcceptable(s: string): boolean;
  }
  let lettersRegexp = /^[A-Za-z]+$/;
  let numberRegexp = /^[0-9]+$/;
  export class LettersOnlyValidator implements StringValidator {
    isAcceptable(s: string){
      return lettersRegexp.test(s);
    }
  }
  export class ZipStrValidator implements StringValidator {
    isAcceptable(s: string){
      return s.length === 5 && numberRegexp.test(s);
    }
  }
}
let strings = ["Hello", "98052", "101"];
let validators: {[s: string]: Validation.StringValidator;} = {};
validators['ZIP code'] = new Validation.ZipStrValidator();
validators['Letters only'] = new Validation.LettersOnlyValidator();

for(let s of strings){
  for(let name in validators){
    let isMatch = validators[name].isAcceptable(s);
    console.log(`'${ s }' ${ isMatch ? "matches" : "does not match" } '${ name }'.`);
  }
}
// Namespaces in multiple files
/// <reference path="namespace-validate.ts" />
/// <reference path="namespace-letters.ts" />
/// <reference path="namespace-zipcode.ts" />

let strings = ["Hello", "98052", "101"];
let validators: { [s: string]: Validation.StringValidator; } = {};
validators["ZIP code"] = new Validation.ZipCodeValidator();
validators["Letters only"] = new Validation.LettersOnlyValidator();

for (let s of strings) {
  for (let name in validators) {
    console.log(`"${ s }" - ${ validators[name].isAcceptable(s) ? "matches" : "does not match" } ${ name }`);
  }
}

Namespaces and modules

Namespace: A common JavaScript object with a name that resides in the global namespace
Disadvantages: Just like other global namespace pollution, it is difficult to identify dependencies between components, especially in large applications

Modules: Modules can contain code and declarations, unlike namespaces, they can declare their dependencies
Note: Modules provide good code reuse, greater closeness, and better tool optimization

Posted by lush_pierre on Fri, 06 Sep 2019 09:17:43 -0700