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

19. 三斜线指令

19. 三斜线指令1. 概述三斜线指令是 TypeScript 中的特殊注释用于在编译时引入依赖关系。它们告诉 TypeScript 编译器在编译过程中包含其他文件。虽然现代 TypeScript 项目推荐使用 ES 模块但三斜线指令在特定场景下仍然有用。┌─────────────────────────────────────────────────────────────┐ │ 三斜线指令系统 │ ├─────────────────────────────────────────────────────────────┤ │ │ │ 指令类型 │ │ ├──/// reference path... /文件路径引用 ││ ├──/// reference types... /类型包引用 ││ ├──/// reference lib... /内置库引用 ││ └──/// reference no-default-libtrue/禁用默认库 ││ │ │ 适用场景 │ │ ├── 全局类型声明文件 │ │ ├── 没有模块系统的旧项目 │ │ ├── 编译时依赖管理 │ │ └── 声明文件中的依赖 │ │ │ └─────────────────────────────────────────────────────────────┘2. 三斜线指令语法三斜线指令是单行注释必须以三个斜杠开头。/// reference path... //// reference types... //// reference lib... //// reference no-default-libtrue/3. path 指令path指令用于指定依赖文件路径。3.1 基本用法// types/global.d.tsinterfaceGlobalConfig{apiUrl:string;timeout:number;}declareconstCONFIG:GlobalConfig;// main.ts/// reference path./types/global.d.ts /console.log(CONFIG.apiUrl);// TypeScript 知道 CONFIG 的类型3.2 多文件引用// types/math.d.tsdeclarefunctionadd(a:number,b:number):number;declarefunctionmultiply(a:number,b:number):number;// types/string.d.tsdeclarefunctiontoUpperCase(str:string):string;declarefunctiontoLowerCase(str:string):string;// main.ts/// reference path./types/math.d.ts //// reference path./types/string.d.ts /constsumadd(5,3);// 5constuppertoUpperCase(hello);// HELLO4. types 指令types指令用于引用 DefinitelyTyped 中的类型定义包。/// reference typesnode //// reference typesjest /// 现在可以使用 Node.js 和 Jest 的类型importfsfromfs;constcontentfs.readFileSync(file.txt,utf-8);5. lib 指令lib指令用于显式引用内置库。/// reference libes2015 //// reference libdom //// reference libwebworker /// 可以使用 ES2015 和 DOM 的类型constpromisePromise.resolve(42);constelementdocument.getElementById(app);6. no-default-lib 指令no-default-lib指令用于禁用默认库。/// reference no-default-libtrue/// 这个文件不会包含默认的 lib.d.ts// 通常用于自定义运行环境7. 完整示例全局类型系统// 1. 类型声明文件 // types/globals.d.ts// 全局变量声明declareconstAPP_VERSION:string;declareconstAPP_NAME:string;declareconstDEBUG:boolean;// 全局函数声明declarefunctionlog(message:string):void;declarefunctionwarn(message:string):void;declarefunctionerror(message:string):void;// 全局类声明declareclassLogger{constructor(prefix:string);log(message:string):void;setLevel(level:debug|info|error):void;}// 全局命名空间declarenamespaceUtils{functionformatDate(date:Date):string;functionformatNumber(num:number):string;functiongenerateId():string;}// 接口扩展declareglobal{interfaceWindow{__INITIAL_STATE__:any;__REDUX_DEVTOOLS_EXTENSION__:any;}interfaceArrayT{last():T|undefined;first():T|undefined;}}// 导出用于模块化export{};// 2. 实现文件 // src/globals.ts/// reference path../types/globals.d.ts /// 实现全局变量(windowasany).APP_VERSION1.0.0;(windowasany).APP_NAMEMyApp;(windowasany).DEBUGprocess.env.NODE_ENVdevelopment;// 实现全局函数functionlog(message:string){console.log([LOG]${message});}functionwarn(message:string){console.warn([WARN]${message});}functionerror(message:string){console.error([ERROR]${message});}// 实现全局类classLogger{privateprefix:string;privatelevel:debug|info|errorinfo;constructor(prefix:string){this.prefixprefix;}log(message:string){if(this.leveldebug){console.log([${this.prefix}]${message});}}setLevel(level:debug|info|error){this.levellevel;}}// 实现命名空间namespaceUtils{exportfunctionformatDate(date:Date):string{returndate.toISOString().split(T)[0];}exportfunctionformatNumber(num:number):string{returnnum.toLocaleString();}exportfunctiongenerateId():string{return${Date.now()}-${Math.random().toString(36).substr(2,9)};}}// 实现数组扩展Array.prototype.lastfunction(){returnthis[this.length-1];};Array.prototype.firstfunction(){returnthis[0];};// 3. 使用文件 // src/main.ts/// reference path../types/globals.d.ts /// 使用全局变量console.log(App:${APP_NAME}v${APP_VERSION});if(DEBUG){console.log(Debug mode enabled);}// 使用全局函数log(Application started);warn(This is a warning);error(This is an error);// 使用全局类constloggernewLogger(MyApp);logger.log(Hello);// 使用命名空间constformattedDateUtils.formatDate(newDate());constformattedNumberUtils.formatNumber(1234567);constidUtils.generateId();console.log({formattedDate,formattedNumber,id});// 使用扩展的数组方法constarr[1,2,3];console.log(arr.first());// 1console.log(arr.last());// 3// 使用全局接口扩展window.__INITIAL_STATE__{user:Alice};console.log(window.__INITIAL_STATE__);8. 三斜线指令 vs 模块导入特性三斜线指令ES 模块导入语法/// reference path... /import { x } from ./module作用域全局模块类型安全一般强推荐程度旧项目、特殊场景现代项目依赖管理手动自动Tree Shaking不支持支持9. 实际应用场景9.1 声明文件中的依赖// jquery.d.ts/// reference typessizzle /declaremodulejquery{exportjQuery;}9.2 测试文件引用// test/setup.ts/// reference typesjest //// reference path../types/global.d.ts /// 测试配置代码beforeEach((){// setup});9.3 编译时配置// tsconfig.json 配合使用{compilerOptions:{types:[node,jest]}}// 或在文件中使用三斜线指令覆盖配置/// reference libes2020 /10. 注意事项注意事项说明位置限制三斜线指令必须在文件顶部只允许注释或空行在前模块冲突如果文件有 import/export三斜线指令会被忽略性能影响过多使用会影响编译性能推荐替代新项目应使用 tsconfig.json 的 include 和 ES 模块11. 总结指令用途示例path引用本地文件/// reference path./types.d.ts /types引用类型包/// reference typesnode /lib引用内置库/// reference libes2015 /no-default-lib禁用默认库/// reference no-default-libtrue/
http://www.rkmt.cn/news/1363393.html

相关文章:

  • 范畴论视角下的概率机器学习:从Giry单子到贝叶斯推理的统一框架
  • 基于决策树与贝叶斯DNS的宏观机制转换利率模型
  • Dingo-BNS:基于神经后验估计的亚秒级引力波参数推断框架
  • DL:Transformer 的基本原理与 PyTorch 实现
  • 26年5月系统架构设计师论文真题题目分析
  • [智能体-39]:硅基重构世间秩序:AI模块化协同下的人生、创业与社会哲学
  • 安卓7+ HTTPS抓包失效原因与ADB证书注入方案
  • 对抗性环境下基于分布鲁棒优化的k-次模拦截问题求解
  • 基于树莓派与YOLOv8的铁路道口智能安全系统全栈实践
  • 在国产银河麒麟V10上搞定VMware Workstation 17 Pro,手把手教你从下载到创建第一个虚拟机
  • Necesse 多人沙盒生存 RPG 服务器搭建教程
  • 司法AI风险评估:性能与公平性的技术悖论与工程实践
  • LeetCode 1248:统计「优美子数组」 | 前缀和与奇数计数
  • 如何3步完成硬件适配:终极自动化配置指南
  • APS与RAPS:置信预测中覆盖保证与集合效率的权衡解析
  • 鸿蒙electron跨端框架PC墨案写作实战:把 Markdown 正文区做成桌面写作的中心
  • 大语言模型在临床试验预测与优化中的应用与挑战
  • Vision Mamba边缘部署:从算法瓶颈到专用硬件加速器设计
  • 2026年4月商用中央空调直销厂家口碑推荐,口碑好的商用中央空调哪家好,空气循环,保持室内空气新鲜 - 品牌推荐师
  • LeetCode 523:连续的子数组和 | 前缀和同余定理
  • LeetCode 238:除自身以外数组的乘积 | 前缀积与后缀积
  • SMGI框架:通用人工智能的结构元模型与实现路径解析
  • Win10/Win11频繁蓝屏DPC_WATCHDOG_VIOLATION?别慌,用WinDBG的!dpcwatchdog命令5分钟定位元凶
  • Autumn Valley资源包:开放世界性能优化实战指南
  • 基于FeFET的动态可重构FPGA:实现亚纳秒级上下文切换的硬件加速新架构
  • Burp Suite扫描深度配置指南:被动扫描、主动扫描与自定义插入点协同调优
  • Unity第一人称射击骨架:视角稳定、帧级响应与物理化弹道实现
  • CAD+MLIP:高效计算固体振动自由能与热力学性质的技术实践
  • 统信UOS/麒麟KYLINOS系统管理员必备:一键脚本批量清除所有用户的数科OFD阅读历史
  • 除了Easy App Locker,还有哪些Mac应用加锁方案?横向对比与避坑指南