当前位置: 首页 > news >正文

TypeScript基础篇 - TS模块

目录

模块的概念

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"]
}

http://www.lryc.cn/news/100201.html

相关文章:

  • 安卓:Picasso——加载网络图片的库
  • 1468-PIPI的魔咒
  • 3d激光slam建图与定位(1)_基于ndt算法定位
  • 云安全攻防(二)之 云原生安全
  • 最后的组合:K8s 1.24 基于 Hekiti 实现 GlusterFS 动态存储管理实践
  • 笙默考试管理系统-MyExamTest(16)
  • 初级算法-树
  • Harbor Failed to start docker.service: Unit docker.service not found.
  • 网络安全/信息安全(黑客技术)自学笔记
  • ADB 命令结合 monkey 的简单使用,超详细
  • 级联选择框
  • 如何在3ds max中创建可用于真人场景的巨型机器人:第 5 部分
  • 【MATLAB第61期】基于MATLAB的GMM高斯混合模型回归数据预测
  • Mnist分类与气温预测任务
  • Pytorch深度学习-----神经网络的卷积操作
  • 微信小程序转抖音小程序的坑:The component <xxx> used in pages/xxx/xxx is undefined
  • Vue+element Ui的el-select同时获取value和label的方法总结
  • 乐划锁屏充分发挥强创新能力,打造内容业新生态
  • 防御第三天
  • 用JavaScript和HTML实现一个精美的计算器
  • 基于postgresl的gaussDB(DWS)地址省市区解析函数
  • 【Golang】Golang进阶系列教程--Go 语言 new 和 make 关键字的区别
  • Day 9 C++ 内存分区模型
  • STM32 CubeMX 定时器(普通模式和PWM模式)
  • mysql清除主从复制关系
  • Spring Cloud Eureka 服务注册和服务发现超详细(附加--源码实现案例--及实现逻辑图)
  • 【docker】docker部署nginx
  • 苍穹外卖-day08
  • 【matlab】机器人工具箱快速上手-动力学仿真(代码直接复制可用)
  • MySQL高级篇第2章(MySQL的数据目录)