developerasun / myCodeBox-web

Open source code box for web developers.
Apache License 2.0
5 stars 0 forks source link

[RESEARCH] typescript/module: export and import #271

Open developerasun opened 2 years ago

developerasun commented 2 years ago

topic : understanding various export/import approaches in Typescript

read this

Any declaration (such as a variable, function, class, type alias, or interface) can be exported by adding the export keyword.

// export function signature
export interface StringValidator {
  isAcceptable(s: string): boolean;
}

Export statements are handy when exports need to be renamed for consumers, so the above example can be written as:

export { ZipCodeValidator as mainValidator };

Optionally, a module can wrap one or more modules and combine all their exports using export * from "module" syntax.

export * from "./StringValidator"; // exports 'StringValidator' interface
export * from "./ZipCodeValidator"; // exports 'ZipCodeValidator' class and 'numberRegexp' constant value
export * from "./ParseIntBasedZipCodeValidator"; //  exports the 'ParseIntBasedZipCodeValidator' class
// and re-exports 'RegExpBasedZipCodeValidator' as alias
// of the 'ZipCodeValidator' class from 'ZipCodeValidator.ts'
// module.

imports can also be renamed

import { ZipCodeValidator as ZCV } from "./ZipCodeValidator";
let myValidator = new ZCV();

import the entire module into a single variable, and use it to access the module exports

import * as validator from "./ZipCodeValidator";
let myValidator = new validator.ZipCodeValidator();

Prior to TypeScript 3.8, you can import a type using import. With TypeScript 3.8, you can import a type using the import statement, or using import type.

// Re-using the same import
import { APIResponseType } from "./api";
// Explicitly use import type
import type { APIResponseType } from "./api";

import type is always guaranteed to be removed from your JavaScript, and tools like Babel can make better assumptions about your code via the isolatedModules compiler flag

reference