在ES6前, 常用的模组概念是 CommonJS , require 引入模组与 exports 汇出模组。 到了 ES6 则新增了 import 与 export 来进行引入汇出的方式。TypeScript 也沿用支援。今天来了解 ES Module Syntax 、 TypeScript 的 ES Module Syntax 、CommonJS Syntax。
若有错误,欢迎留言指教,感恩的心。
只汇出一个变数或function等,可使用 export default
:
// @filename: hello.ts
export default function helloWorld() {
console.log("Hello, world!");
}
import name
from
import hello from "./hello.js";
hello();
如果要汇出的变数或function等不只一个,可使用 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;
}
import {name
} from
import { pi, phi, absolute } from "./maths.js";
console.log(pi);
const absPhi = absolute(phi);
const absPhi: number
name
fromname
} from除了上面普遍使用的2种 import 方法,还有一些有关import的用法:
使用关键字as
:
import { pi as π } from "./maths.js";
console.log(π);
// @filename: maths.ts
export const pi = 3.14;
export default class RandomNumberGenerator {}
使用 ,
去衔接:
// @filename: app.ts
import RNGen, { pi as π } from "./maths.js";
console.log(π);
* as name
take all into a single namespace汇入全部*
并命名 math
:
import * as math from "./maths.js";
console.log(math.pi);
const positivePhi = math.absolute(math.phi);
import "./file"
直接汇入档案执行:
// @filename: app.ts
import "./maths.js";
console.log("3.14");
// @filename: animal.ts
export type Cat = { breed: string; yearOfBirth: number };
export interface Dog {
breeds: string[];
yearOfBirth: number;
}
// @filename: app.ts
import { Cat, Dog } from "./animal.js";
type Animals = Cat | Dog;
// @filename: animal.ts
export type Cat = { breed: string; yearOfBirth: number };
export type Dog = { breeds: string[]; yearOfBirth: number };
export const createCatName = () => "fluffy";
// @filename: valid.ts
import type { Cat, Dog } from "./animal.js";
export type Animals = Cat | Dog;
// @filename: app.ts
import type { createCatName } from "./animal.js";
const name = createCatName();
// @filename: app.ts
import { createCatName, type Cat, type Dog } from "./animal.js";
export type Animals = Cat | Dog;
const name = createCatName();
function absolute(num: number) {
if (num < 0) return num * -1;
return num;
}
module.exports = {
pi: 3.14,
squareTwo: 1.41,
phi: 1.61,
absolute,
};
const maths = require("maths");
maths.pi;
const { squareTwo } = require("maths");
squareTwo;
感谢阅读,明天见!
https://www.typescriptlang.org/docs/handbook/2/modules.html
>>: 程序中出现问号(?)跟冒号(:),这是什麽表达方式?
今天就废话不多说把注册页写完吧! 注册页 一样先来构思画面,由上而下AppBar,标题,描述文字,e...
数据流图为组织理解、完善和实施新流程或系统提供了一种直接、有效的方式。它们是您的流程或系统的可视化表...
一个 控制目标(control objectives) 是一个“描述的是要实现作为实施控制的结果声明...
取号机制是专案中很常会使用到的项目。在我们的生活中小到饮料店的取餐单、银行的号码牌, 大到公文系统的...
不怎麽重要的前言 上一篇介绍了if条件式的语法,让我们可以依照设定好的条件来执行不同内容。 这次我们...