郓城县网站建设网站建设改代码改哪些
目录
模块的概念
Export 语法(default)
Export 语法(non-default)
import 别名
Type Export语法【TS】
模块相关配置项:module【tsconfig.json】
模块相关配置项:moduleResolution
小节总结
模块的概念
【程序包,最基本的封装单元,最基本的单位就是文件,如果没有export,那么ts不会把你当作是一个模块】
- 模块是一个程序的集合(函数、变量、Class等)
 - 模块是可见域的分离:模块内的成员仅仅在包内可见,包外成员无法访问
 - 模块可以主动Export【输出,暴露出】成员:例如用`import/export`语法。
 
Export 语法(default)
// @filename:hello.js
export default function helloWorld() {console.log("Hello, world!");
} 
引用上面暴漏出的方法
import hello from './hello.js'
hello() 
Export 语法(non-default)
// @filename: matchs.js
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 { pi ,phi, absolute } from "./maths.js";console.log(pi,phi);
console.log(absolute(phi)) 
import 别名
import{ pi as pai } from './maths.js';
console.log(pai) 
Type Export语法【TS】
// @filename: animal.ts
export type Cat = { breed: string; yearOfBirth: number}
export interface Dog {} 
使用上面暴漏出的方法
import {Cat} from './animal.ts' // 一样用
import type {Cat} from './animal.ts' 
// 如果Cat是个实际类,也可以这样引用,但是不能new Cat 
模块相关配置项:module【tsconfig.json】
- ES6
 - ES2015
 - ES2020
 - ESNext 【最新版本ES】
 - UMD/AMD/Commonjs/SYSTEM
 
模块相关配置项:moduleResolution
- node【通常用这个查找顺序的方法】
 

- classic【查找模块的方法顺序】
 

小节总结
- 为什么抽象模块?隔离和封装
 
1.隔离,让外部看不到模块内部的成员,避免大量成员的全局冲突
2.避免让用户使用起来感到复杂,觉得这个模块很复杂,开箱即用,封装就是把功能封装进去
- 模块解析通常用node还classic? node【node不是默认项,需要设置一下】
 
// @filename: tsconfig.json
{"compilerOptions": {"target": "ES6","lib" : ["DOM", "ESNext"],"moduleResolution": "node","esModuleInterop": true },"include": ["src/**/*.ts"]
} 
