# 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 ascript
whose contents are available in theglobal scope
- any file
containing
a top-levelimport
orexport
is considered amodule
# ES Module Syntax
- you can have
more
than oneexport
of variables and functions via theexport
, butMUST
by omittingdefault
(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 canonly
import types
- an
// 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 a
1 to 1
match in your TypeScript file with the CommonJS output
- directly correlates to a CommonJS and AMD
import fs = require("fs");
const code = fs.readFileSync("hello.ts", "utf8");
# CommonJS Syntax
- CommonJS is the
format
which most modules onnpm
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 ... >.<!