Skip to content

三斜线指令(Triple-Slash Directive)

用于在文件间显式地声明依赖关系。它的主要作用是告诉 TypeScript 编译器「这个文件依赖于另一个文件或类型声明」。

ts
/// <reference path="xxx.d.ts" />
/// <reference types="xxx" />
/// <reference lib="esnext" />

引用路径指令

ts
/// <reference path="xxx.d.ts" />

引入另一个文件或声明文件。

用于:

  • 旧项目中(非模块系统)
  • 多文件之间需要显式依赖
ts
// utils.d.ts
declare function add(a: number, b: number): number;

// main.ts
/// <reference path="./utils.d.ts" />
add(1, 2);

注意:

现代模块化项目(如使用 import/export)一般不需要这种方式。

引用类型指令

引入一个 npm 包的类型声明。

ts
/// <reference types="node" />

引入 Node.js 的类型声明。这种写法常出现在库的类型声明文件中.d.ts,以提供对 Node.js 全局对象的类型支持。

引用库指令

告诉编译器引入指定的 内置库声明(如 ES2020、DOM)。

ts
/// <reference lib="esnext" />
/// <reference lib="dom" />

相当于在 tsconfig.json 中:

json
{
  "compilerOptions": {
    "lib": ["esnext", "dom"]
  }
}

使用场景

类型作用常见场景
path引入具体文件或声明老项目、非模块代码
types引入 npm 包的类型库类型声明文件
lib引入标准库类型指定运行环境(DOM、ESNext)

注意:

  • 使用 ES 模块系统(import/export)时几乎不再需要 reference path。
  • types 和 lib 更常用于 声明文件 或 类型定义包。
  • 如果你使用了 tsconfig.json 的 "typeRoots" 或 "types" 配置,也可以无需手动写 reference types