# Modules

import export module.exports = export {} import *

TIP

Modules are executed within their own scope, not in the global scope. This means that variables, functions, classes, etc. declared in a module are not visible outside the module unless they are explicitly exported using one of the export forms.
Conversely, to consume a variable, function, class, interface, etc. exported from a different module, it has to be imported using one of the import forms

  • a file without any top-level import or export declarations is treated as a script whose contents are available in the global scope
  • any file containing a top-level import or export is considered a module

# ES Module Syntax

  • you can have more than one export of variables and functions via the export, but MUST by omitting default (one module only one default)
// @filename: hello.ts
export default function helloWorld() {
 console.log("Hello, world!");
}
...
import hello from "./hello.js"; // hello as alias as default
hello();
//----------  mutilple export
// @filename: maths.ts
export var pi = 3.14;
export let squareTwo = 1.41;
export const phi = 1.61;
export class RandomNumberGenerator {}
export function absolute(num: number) {
 if (num < 0) return num * -1;
 return num;
}
...
mport { pi, phi, absolute } from "./maths.js";
console.log(pi);
const absPhi = absolute(phi);

# Import Syntax

//------ rename
import { pi as π } from "./maths.js";
console.log(π);

//---- mix
import RNGen, { pi as π } from "./maths.js";

//---- all
import * as math from "./maths.js";

// ---- not include any variables , could trigger side-effects
import "./maths.js";

  • import type
    • an import statement which can only import types
// a.js
export type Cat = { };
export type Dog = { };
export const func = () => "fluffy";

import type { Cat, Dog } from "./a.js";
export type Animals = Cat | Dog; // ok

//cannot be used as a value because it was imported using 'import type'
import type { func } from "./a.js";
const name = func(); // error
  • but u can correct above using inline type imports
import { createCatName, type Cat, type Dog } from "./animal.js"; // type X
 
export type Animals = Cat | Dog;
const name = createCatName();
  • ES Module Syntax with CommonJS Behavior
    • directly correlates to a CommonJS and AMD require
    • ensures you have a1 to 1 match in your TypeScript file with the CommonJS output
import fs = require("fs");
const code = fs.readFileSync("hello.ts", "utf8");

# CommonJS Syntax

  • CommonJS is the format which most modules on npm are delivered in
  • Even if you are writing using the ES Modules syntax above, having a brief understanding of how CommonJS syntax works will help you debug easier
  • yiki: well, I don't really understand this part, pls view offical docs ... >.<!
Last Updated: 2021/11/19 上午11:23:03