Skip to main content

triple-slash-reference

Disallow certain triple slash directives in favor of ES6-style import declarations.

ESLint 配置 中扩展"plugin:@typescript-eslint/recommended" 可启用此规则。


TypeScript 的 /// 三斜杠引用是一种指示文件中可以使用另一个模块的类型的方法。 通常不鼓励使用三斜杠引用类型指令,而是使用 ECMAScript 模块 import。 此规则报告 /// <reference lib="..." />/// <reference path="..." />/// <reference types="..." /> 指令的使用。

英:TypeScript's /// triple-slash references are a way to indicate that types from another module are available in a file. Use of triple-slash reference type directives is generally discouraged in favor of ECMAScript Module imports. This rule reports on the use of /// <reference lib="..." />, /// <reference path="..." />, or /// <reference types="..." /> directives.

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/triple-slash-reference": "error"
}
};
在线运行试试这个规则 ↗

选项

可以将三种引用中的任意数量指定为选项。 指定 'always' 会禁用该类型引用的 lint 规则。

英:Any number of the three kinds of references can be specified as an option. Specifying 'always' disables this lint rule for that kind of reference.

lib

当设置为 'never' 时,禁止 /// <reference lib="..." /> 并强制使用 import

英:When set to 'never', bans /// <reference lib="..." /> and enforces using an import instead:

/// <reference lib="code" />

globalThis.value;
Open in Playground

path

当设置为 'never' 时,禁止 /// <reference path="..." /> 并强制使用 import

英:When set to 'never', bans /// <reference path="..." /> and enforces using an import instead:

/// <reference path="code" />

globalThis.value;
Open in Playground

types

当设置为 'never' 时,禁止 /// <reference types="..." /> 并强制使用 import

英:When set to 'never', bans /// <reference types="..." /> and enforces using an import instead:

/// <reference types="code" />

globalThis.value;
Open in Playground

types 选项也可以被赋予 "prefer-import" 值。 这样做表明规则仅应在同一位置已存在 import 时报告:

英:The types option may alternately be given a "prefer-import" value. Doing so indicates the rule should only report if there is already an import from the same location:

/// <reference types="code" />

import { valueA } from 'code';

globalThis.valueB;
Open in Playground

何时不使用它

大多数现代 TypeScript 项目通常使用 import 语句来引入类型。 在自动生成的代码之外很少需要 /// 三斜杠引用。 如果你的项目是一个罕见的具有这些用例之一的项目,那么这条规则可能不适合你。 你可以考虑在这些特定情况下使用 ESLint 禁用注释,而不是完全禁用此规则。

英:Most modern TypeScript projects generally use import statements to bring in types. It's rare to need a /// triple-slash reference outside of auto-generated code. If your project is a rare one with one of those use cases, this rule might not be for you. You might consider using ESLint disable comments for those specific situations instead of completely disabling this rule.

何时不使用它

如果你想使用所有风格的三斜杠参考指令。

英:If you want to use all flavors of triple slash reference directives.

选项

该规则接受以下选项

type Options = [
{
lib?: 'always' | 'never';
path?: 'always' | 'never';
types?: 'always' | 'never' | 'prefer-import';
},
];

const defaultOptions: Options = [
{ lib: 'always', path: 'never', types: 'prefer-import' },
];

资源