export = and import = require()

export = and import = require()

Both CommonJS and AMD generally have the concept of an exports object which contains all exports from a module.

They also support replacing the exports object with a custom single object. Default exports are meant to act as a replacement for this behavior; however, the two are incompatible. TypeScript supports export = to model the traditional CommonJS and AMD workflow.

The export = syntax specifies a single object that is exported from the module. This can be a class, interface, namespace, function, or enum.

When importing a module using export =, TypeScript-specific import let = require("module") must be used to import the module.

ZipCodeValidator.ts
1
2
3
4
5
6
7
let numberRegexp = /^[0-9]+$/;
class ZipCodeValidator {
  isAcceptable(s: string) {
    return s.length === 5 && numberRegexp.test(s);
  }
}
export = ZipCodeValidator;
Test.ts
1
2
3
4
5
6
7
8
9
10
11
12
import zip = require("./ZipCodeValidator");
 
// Some samples to try
let strings = ["Hello", "98052", "101"];
 
// Validators to use
let validator = new zip();
 
// Show whether each string passed each validator
strings.forEach(s => {
  console.log(`"${ s }" - ${ validator.isAcceptable(s) ? "matches" : "does not match" }`);
});
doc_TypeScript
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.