@typescript-eslint/parser
用于将 TypeScript 代码解析为 ESLint 兼容节点以及提供支持 TypeScript 程序的 ESLint 解析器。✨
¥An ESLint parser used to parse TypeScript code into ESLint-compatible nodes, as well as provide backing TypeScript programs. ✨
这是必要的,因为 TypeScript 会生成一种与 ESLint 工作所需的格式不同且不兼容的 AST 格式。例如,这不是有效的 JavaScript 代码,因为它包含 : number
类型注释:
¥This is necessary because TypeScript produces a different, incompatible AST format to the one that ESLint requires to work.
For example, this is not valid JavaScript code because it contains the : number
type annotation:
let x: number = 1;
ESLint 的原生 Espree 解析器在尝试解析它时会引发错误。
¥ESLint's native Espree parser would raise an error attempting to parse it.
此外,由于 TypeScript 是单独开发的,并且与 ESLint、ESTree 和 Espree 的目标不同,因此它的 AST 在许多情况下也以不同的方式表示节点。TS 的 AST 针对解析不完整代码和类型检查的用例进行了优化。ESTree 未经优化,适用于遍历 AST 的 "通用目的" 用例。
¥Additionally, because TypeScript is developed separately and with different goals from ESLint, ESTree, and Espree, its AST also represents nodes differently in many cases. TS's AST is optimized for its use case of parsing incomplete code and typechecking. ESTree is unoptimized and intended for "general purpose" use-cases of traversing the AST.
你可以通过选择 ESTree 在 typescript-eslint 在线运行 的右侧栏上选择 @typescript-eslint/parser
。
¥You can select @typescript-eslint/parser
on the typescript-eslint playground's right sidebar by selecting ESTree.
配置
¥Configuration
通过在 ESLint 配置文件中的 parserOptions
中指定以下附加配置选项,可以使用它们。
¥The following additional configuration options are available by specifying them in parserOptions
in your ESLint configuration file.
interface ParserOptions {
cacheLifetime?: {
glob?: number | 'Infinity';
};
disallowAutomaticSingleRunInference?: boolean;
ecmaFeatures?: {
jsx?: boolean;
globalReturn?: boolean;
};
ecmaVersion?: number | 'latest';
emitDecoratorMetadata?: boolean;
experimentalDecorators?: boolean;
isolatedDeclarations?: boolean;
extraFileExtensions?: string[];
jsDocParsingMode?: 'all' | 'none' | 'type-info';
jsxFragmentName?: string | null;
jsxPragma?: string | null;
lib?: string[];
programs?: import('typescript').Program[];
project?: string | string[] | boolean | null;
projectFolderIgnoreList?: string[];
projectService?: boolean | ProjectServiceOptions;
tsconfigRootDir?: string;
warnOnUnsupportedTypeScriptVersion?: boolean;
}
disallowAutomaticSingleRunInference
默认
process.env.TSESTREE_SINGLE_RUN
或true
。¥Default
process.env.TSESTREE_SINGLE_RUN
ortrue
.
是否停止使用常见的启发式方法来推断 ESLint 是否被用作单次运行的一部分(而不是 --fix
模式或在持久会话(如编辑器扩展)中)。换句话说,typescript-eslint 默认速度更快,并且此选项禁用自动性能优化。
¥Whether to stop using common heuristics to infer whether ESLint is being used as part of a single run (as opposed to --fix
mode or in a persistent session such as an editor extension).
In other words, typescript-eslint is faster by default, and this option disables an automatic performance optimization.
当 typescript-eslint 在后台处理 使用类型信息进行 linting 的 TypeScript 程序管理时,这种区别对于性能很重要。管理长期运行用例所需的 TypeScript "观察" 程序会产生大量开销。能够假设单次运行的情况允许 typescript-eslint 更快地运行不可变程序。
¥When typescript-eslint handles TypeScript Program management behind the scenes for linting with type information, this distinction is important for performance. There is significant overhead to managing TypeScript "Watch" Programs needed for the long-running use-case. Being able to assume the single run case allows typescript-eslint to faster immutable Programs instead.
可以通过将 TSESTREE_SINGLE_RUN
环境变量设置为 "false"
或 "true"
来指定此设置的默认值。例如,TSESTREE_SINGLE_RUN=false npx eslint .
将禁用它。
¥This setting's default value can be specified by setting a TSESTREE_SINGLE_RUN
environment variable to "false"
or "true"
.
For example, TSESTREE_SINGLE_RUN=false npx eslint .
will disable it.
我们建议尽可能关闭此选项。我们已经看到允许自动单次运行推断可将 CI 中的 linting 速度提高高达 10-20%。
¥We recommend leaving this option off if possible. We've seen allowing automatic single run inference improve linting speed in CI by up to 10-20%.
cacheLifetime
此选项允许你精细地控制我们的内部缓存过期长度。
¥This option allows you to granularly control our internal cache expiry lengths.
你可以将秒数指定为整数,如果你不想让缓存过期,则可以指定字符串 '无限'。
¥You can specify the number of seconds as an integer number, or the string 'Infinity' if you never want the cache to expire.
默认情况下,缓存条目将在 30 秒后被逐出,或者如果解析器推断它是单次运行(参见 disallowAutomaticSingleRunInference
),则将无限期地持续存在。
¥By default cache entries will be evicted after 30 seconds, or will persist indefinitely if the parser infers that it is a single run (see disallowAutomaticSingleRunInference
).
ecmaFeatures
用于描述如何解析原始语法的可选附加选项。
¥Optional additional options to describe how to parse the raw syntax.
jsx
默认
false
。¥Default
false
.
在 true
时启用解析 JSX。更多详细信息可在 TypeScript 手册的 JSX 文档 中找到。
¥Enable parsing JSX when true
.
More details can be found in the TypeScript handbook's JSX docs.
注意:此设置不影响已知文件类型(.js
、.mjs
、.cjs
、.jsx
、.ts
、.mts
、.cts
、.tsx
、.json
),因为 TypeScript 编译器对已知文件扩展名有自己的内部处理。
¥NOTE: this setting does not affect known file types (.js
, .mjs
, .cjs
, .jsx
, .ts
, .mts
, .cts
, .tsx
, .json
) because the TypeScript compiler has its own internal handling for known file extensions.
确切的行为如下:
¥The exact behavior is as follows:
-
.js
、.mjs
、.cjs
、.jsx
、.tsx
文件始终被解析为true
。¥
.js
,.mjs
,.cjs
,.jsx
,.tsx
files are always parsed as if this istrue
. -
.ts
、.mts
、.cts
文件始终被解析为false
。¥
.ts
,.mts
,.cts
files are always parsed as if this isfalse
. -
对于 "unknown" 扩展(
.md
、.vue
):¥For "unknown" extensions (
.md
,.vue
):-
如果未提供
parserOptions.project
:¥If
parserOptions.project
is not provided:-
该设置将受到尊重。
¥The setting will be respected.
-
-
如果提供
parserOptions.project
(即你正在使用带有类型信息的规则):¥If
parserOptions.project
is provided (i.e. you are using rules with type information):-
始终解析为
false
¥always parsed as if this is
false
-
-
globalReturn
默认
false
。¥Default
false
.
此选项允许你告诉解析器是否要在代码库中允许全局 return
语句。
¥This options allows you to tell the parser if you want to allow global return
statements in your codebase.
ecmaVersion
默认
2018
。¥Default
2018
.
接受任何有效的 ECMAScript 版本号或 'latest'
:
¥Accepts any valid ECMAScript version number or 'latest'
:
-
厌恶:es3、es5、es6、es7、es8、es9、es10、es11、es12、es13、...或
¥A version: es3, es5, es6, es7, es8, es9, es10, es11, es12, es13, ..., or
-
一年:es2015、es2016、es2017、es2018、es2019、es2020、es2021、es2022,...,或
¥A year: es2015, es2016, es2017, es2018, es2019, es2020, es2021, es2022, ..., or
-
'latest'
当它是版本或年份时,值必须是数字 - 因此不要包含 es
前缀。
¥When it's a version or a year, the value must be a number - so do not include the es
prefix.
指定要使用的 ECMAScript 语法版本。解析器使用它来确定如何执行范围分析,并且它会影响默认值
¥Specifies the version of ECMAScript syntax you want to use. This is used by the parser to determine how to perform scope analysis, and it affects the default
emitDecoratorMetadata
默认
undefined
。¥Default
undefined
.
此选项允许你告诉解析器表现得好像 emitDecoratorMetadata: true
在 tsconfig.json
中设置,但没有 类型感知的 linting。换句话说,在这种情况下,你不必指定 parserOptions.project
,从而使 linting 过程更快。
¥This option allow you to tell parser to act as if emitDecoratorMetadata: true
is set in tsconfig.json
, but without type-aware linting. In other words, you don't have to specify parserOptions.project
in this case, making the linting process faster.
experimentalDecorators
默认
undefined
。¥Default
undefined
.
此选项允许你告诉解析器表现得好像 experimentalDecorators: true
在 tsconfig.json
中设置,但没有 类型感知的 linting。换句话说,在这种情况下,你不必指定 parserOptions.project
,从而使 linting 过程更快。
¥This option allow you to tell parser to act as if experimentalDecorators: true
is set in tsconfig.json
, but without type-aware linting. In other words, you don't have to specify parserOptions.project
in this case, making the linting process faster.
extraFileExtensions
默认
undefined
。¥Default
undefined
.
此选项允许你提供一个或多个在 TypeScript 程序编译中应考虑的附加文件扩展名。默认扩展为 ['.js', '.mjs', '.cjs', '.jsx', '.ts', '.mts', '.cts', '.tsx']
。添加以 .
开头的扩展名,后跟文件扩展名。例如对于 .vue
文件,使用 "extraFileExtensions": [".vue"]
。
¥This option allows you to provide one or more additional file extensions which should be considered in the TypeScript Program compilation.
The default extensions are ['.js', '.mjs', '.cjs', '.jsx', '.ts', '.mts', '.cts', '.tsx']
.
Add extensions starting with .
, followed by the file extension. E.g. for a .vue
file use "extraFileExtensions": [".vue"]
.
有关避免性能问题,请参阅 projectService
对 extraFileExtensions
的更改。
¥See Changes to extraFileExtensions
with projectService
to avoid performance issues.
isolatedDeclarations
默认
undefined
。¥Default
undefined
.
此选项允许你告诉解析器表现得好像 isolatedDeclarations: true
在 tsconfig.json
中设置,但没有 类型感知的 linting。换句话说,在这种情况下,你不必指定 parserOptions.project
,从而使 linting 过程更快。
¥This option allow you to tell parser to act as if isolatedDeclarations: true
is set in tsconfig.json
, but without type-aware linting.
In other words, you don't have to specify parserOptions.project
in this case, making the linting process faster.
jsDocParsingMode
如果设置了
parserOptions.project
,则默认为'all'
,否则为'none'
¥Default if
parserOptions.project
is set, then'all'
, otherwise'none'
当 TS 解析文件时,它还会将 JSDoc 注释解析到 AST 中 - 然后可以被 lint 规则使用。如果你使用的 TypeScript 版本 >=5.3,则此选项可以用作性能优化。
¥When TS parses a file it will also parse JSDoc comments into the AST - which can then be consumed by lint rules. If you are using TypeScript version >=5.3 then this option can be used as a performance optimization.
此规则的有效值为:
¥The valid values for this rule are:
-
'all'
- 始终解析所有 JSDoc 注释。¥
'all'
- parse all JSDoc comments, always. -
'none'
- 永远不解析 JSDoc 注释。¥
'none'
- parse no JSDoc comments, ever. -
'type-info'
- 仅解析提供正确类型信息所需的 JSDoc 注释。TS 总是会解析非 TS 文件中的 JSDoc,但绝不会解析 TS 文件中的 JSDoc。¥
'type-info'
- parse just JSDoc comments that are required to provide correct type-info. TS will always parse JSDoc in non-TS files, but never in TS files.
如果你不使用依赖 TS 的 JSDoc 标签表示的 lint 规则(如 eslint-plugin-deprecation
),则可以将其设置为 'none'
以提高解析器性能。
¥If you do not use lint rules like eslint-plugin-deprecation
that rely on TS's JSDoc tag representation, then you can set this to 'none'
to improve parser performance.
jsxFragmentName
默认
null
¥Default
null
用于 JSX 片段元素的标识符(转译后)。如果是 null
,则假定转译将始终使用已配置的 jsxPragma
的成员。这不应该是成员表达式 - 仅根标识符(即使用 "h"
而不是 "h.Fragment"
)。
¥The identifier that's used for JSX fragment elements (after transpilation).
If null
, assumes transpilation will always use a member of the configured jsxPragma
.
This should not be a member expression - just the root identifier (i.e. use "h"
instead of "h.Fragment"
).
如果你提供 parserOptions.project
,则无需设置它,因为它会自动从编译器中检测到。
¥If you provide parserOptions.project
, you do not need to set this, as it will be automatically detected from the compiler.
jsxPragma
默认
'React'
¥Default
'React'
用于创建 JSX Elements(转译后)的标识符。如果你使用的是 React 以外的库(如 preact
),则应更改此值。如果你使用的是 新的 JSX 转换,你可以将其设置为 null
。
¥The identifier that's used for JSX Elements creation (after transpilation).
If you're using a library other than React (like preact
), then you should change this value. If you are using the new JSX transform you can set this to null
.
这不应该是成员表达式 - 仅根标识符(即使用 "React"
而不是 "React.createElement"
)。
¥This should not be a member expression - just the root identifier (i.e. use "React"
instead of "React.createElement"
).
如果你提供 parserOptions.project
,则无需设置它,因为它会自动从编译器中检测到。
¥If you provide parserOptions.project
, you do not need to set this, as it will be automatically detected from the compiler.
lib
默认
['es2018']
¥Default
['es2018']
有关有效选项,请参阅 TypeScript 编译器选项。
¥For valid options, see the TypeScript compiler options.
指定可用的 TypeScript lib
。范围分析器使用它来确保为 TypeScript 公开的类型声明了全局变量。
¥Specifies the TypeScript lib
s that are available. This is used by the scope analyser to ensure there are global variables declared for the types exposed by TypeScript.
如果你提供 parserOptions.project
,则无需设置它,因为它会自动从编译器中检测到。
¥If you provide parserOptions.project
, you do not need to set this, as it will be automatically detected from the compiler.
programs
默认
undefined
。¥Default
undefined
.
此选项允许你以编程方式提供 TypeScript 程序对象的实例,该对象将为规则提供类型信息。这将覆盖任何从 parserOptions.project
计算出来的程序。所有 linted 文件必须是所提供程序的一部分。
¥This option allows you to programmatically provide an instance of a TypeScript Program object that will provide type information to rules.
This will override any programs that would have been computed from parserOptions.project
.
All linted files must be part of the provided program(s).
有关如何编写 resolveModuleNames
函数的示例,请参阅 TypeScript Wiki。
¥Refer to the TypeScript Wiki for an example on how to write the resolveModuleNames
function.
project
我们现在建议使用 projectService
而不是 project
,以便于配置和更快地进行 linting。
¥We now recommend using projectService
instead of project
for easier configuration and faster linting.
默认
undefined
。¥Default
undefined
.
项目 TSConfig 的路径。此设置或 projectService
是使用 需要类型信息的规则 所必需的。
¥A path to your project's TSConfig. This setting or projectService
are required to use rules which require type information.
接受的值类型:
¥Accepted value types:
// find the tsconfig.json nearest to each source file
project: true,
// path
project: './tsconfig.json';
// glob pattern
project: './packages/**/tsconfig.json';
// array of paths and/or glob patterns
project: ['./packages/**/tsconfig.json', './separate-package/tsconfig.json'];
// ways to disable type-aware linting (useful for overrides configs)
project: false;
project: null;
-
如果是
true
,则每个源文件的解析将找到与该源文件最近的tsconfig.json
文件。¥If
true
, each source file's parse will find the nearesttsconfig.json
file to that source file.-
这是通过检查源文件的目录树以查找最近的
tsconfig.json
来完成的。¥This is done by checking that source file's directory tree for the nearest
tsconfig.json
.
-
-
如果你使用项目引用,TypeScript 将不会自动使用项目引用来解析文件。这意味着你必须将每个引用的 tsconfig 单独或通过 glob 添加到
project
字段。¥If you use project references, TypeScript will not automatically use project references to resolve files. This means that you will have to add each referenced tsconfig to the
project
field either separately, or via a glob. -
请注意,在
parserOptions.project
中使用宽**
可能会导致性能影响。不要使用**
递归检查所有文件夹的 glob,而要选择一次使用单个*
的路径。有关更多信息,请参阅 #2611。¥Note that using wide globs
**
in yourparserOptions.project
may cause performance implications. Instead of globs that use**
to recursively check all folders, prefer paths that use a single*
at a time. For more info see #2611. -
TypeScript 将忽略同一文件夹中具有重复文件名的文件(例如,
src/file.ts
和src/file.js
)。TypeScript 故意忽略除一个文件之外的所有文件,只保留具有最高优先级扩展的一个文件(扩展优先级顺序(从高到低)为.ts
、.tsx
、.d.ts
、.js
、.jsx
)。有关更多信息,请参阅 #955。¥TypeScript will ignore files with duplicate filenames in the same folder (for example,
src/file.ts
andsrc/file.js
). TypeScript purposely ignores all but one of the files, only keeping the one file with the highest priority extension (the extension priority order (from highest to lowest) is.ts
,.tsx
,.d.ts
,.js
,.jsx
). For more info see #955.
如果未设置 tsconfigRootDir
,则相对路径将相对于当前工作目录进行解释。
¥Relative paths are interpreted relative to the current working directory if tsconfigRootDir
is not set.
如果指定了此设置,则必须仅对由提供的 TSConfig 文件定义的项目中包含的文件进行 lint。如果你现有的配置不包含你想要 lint 的所有文件,你可以按如下方式创建单独的 tsconfig.eslint.json
:
¥If this setting is specified, you must only lint files that are included in the projects as defined by the provided TSConfig file(s). If your existing configuration does not include all of the files you would like to lint, you can create a separate tsconfig.eslint.json
as follows:
{
// extend your base config so you don't have to redefine your compilerOptions
"extends": "./tsconfig.json",
"include": [
"src/**/*.ts",
"test/**/*.ts",
"typings/**/*.ts",
// etc
// if you have a mixed JS/TS codebase, don't forget to include your JS files
"src/**/*.js",
],
}
有关允许在你的 TSConfig 文件之外对文件进行 linting 的选项,请参阅 projectService
。
¥For an option that allows linting files outside of your TSConfig file(s), see projectService
.
projectService
默认
false
。¥Default
false
.
指定使用 TypeScript API 为规则生成类型信息。它将自动为每个文件使用最近的 tsconfig.json
(如 project: true
)。它还可以配置为允许在没有 allowJs
编译器选项的情况下计算 JavaScript 文件的类型信息(与 project: true
不同)。
¥Specifies using TypeScript APIs to generate type information for rules.
It will automatically use the nearest tsconfig.json
for each file (like project: true
).
It can also be configured to also allow type information to be computed for JavaScript files without the allowJs
compiler option (unlike project: true
).
- 扁平配置
- 旧版配置
export default [
{
languageOptions: {
parserOptions: {
projectService: true,
},
},
},
];
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
projectService: true,
},
};
此设置或 project
是使用 需要类型信息的规则 所必需的。
¥This setting or project
are required to use rules which require type information.
与旧版 project
相比,此选项有两个主要优点:
¥This option brings two main benefits over the older project
:
-
更简单的配置:大多数项目不需要明确配置
project
路径或创建tsconfig.eslint.json
¥Simpler configurations: most projects shouldn't need to explicitly configure
project
paths or createtsconfig.eslint.json
s -
可预测性:它使用与编辑器相同的类型信息服务,与编辑器中看到的类型具有更好的一致性
¥Predictability: it uses the same type information services as editors, giving better consistency with the types seen in editors
请参阅 常见问题解答 > 类型化 Linting > 项目服务问题 以获取有关使用项目服务的帮助。
¥See FAQs > Typed Linting > Project Service Issues for help on working with the project service.
ProjectServiceOptions
可以通过将 parserOptions.projectService
设置为对象来定制其行为。
¥The behavior of parserOptions.projectService
can be customized by setting it to an object.
{
parser: '@typescript-eslint/parser',
parserOptions: {
projectService: {
allowDefaultProject: ['*.js'],
},
},
};
请参阅 故障排除和常见问题解答 > 类型 Linting > 项目服务问题 以获取使用这些选项的帮助。
¥See Troubleshooting & FAQs > Typed Linting > Project Service Issues for help using these options.
allowDefaultProject
默认
[]
(无)¥Default
[]
(none)
尽管项目服务不匹配,但允许使用默认项目编译器选项运行的文件。它接受一个相对于 tsconfigRootDir
解析的字符串路径数组。
¥Globs of files to allow running with the default project compiler options despite not being matched by the project service.
It takes in an array of string paths that will be resolved relative to the tsconfigRootDir
.
这旨在为未包含在其兄弟 tsconfig.json
中的配置文件(例如 eslint.config.js
)生成类型信息。从默认项目中检索到的每个包含类型信息的文件都会给 linting 带来不小的性能开销。请谨慎使用此选项。
¥This is intended to produce type information for config files such as eslint.config.js
that aren't included in their sibling tsconfig.json
.
Every file with type information retrieved from the default project incurs a non-trivial performance overhead to linting.
Use this option sparingly.
此选项有几个限制,以防止过度使用:
¥There are several restrictions on this option to prevent it from being overused:
-
**
不允许出现在传递给它的 glob 中¥
**
is not allowed in globs passed to it -
与
allowDefaultProject
匹配的文件可能也不会包含在其最近的tsconfig.json
中¥Files that match
allowDefaultProject
may not also be included in their nearesttsconfig.json
defaultProject
默认
'tsconfig.json'
¥Default
'tsconfig.json'
要使用的 TSConfig 路径,而不是 TypeScript 的默认项目配置。它接受一个相对于 tsconfigRootDir
解析的字符串路径。
¥Path to a TSConfig to use instead of TypeScript's default project configuration.
It takes in a string path that will be resolved relative to the tsconfigRootDir
.
projectService.defaultProject
仅影响 allowDefaultProject
包含的 "out-of-project" 文件。
¥projectService.defaultProject
only impacts the "out-of-project" files included by allowDefaultProject
.
loadTypeScriptPlugins
默认
false
¥Default
false
是否应允许项目服务加载 TypeScript 插件。默认情况下,这是 false
,以防止插件注册持久文件监视器或其他可能阻止 ESLint 进程在命令行上运行时退出的操作。
¥Whether the project service should be allowed to load TypeScript plugins.
This is false
by default to prevent plugins from registering persistent file watchers or other operations that might prevent ESLint processes from exiting when run on the command-line.
如果你的项目配置了与 TypeScript 插件交互的自定义规则,则在编辑器中启用此功能可能会很有用。例如,仅在 VS Code 中运行时启用此选项:
¥If your project is configured with custom rules that interact with TypeScript plugins, it may be useful to turn this on in your editor. For example, only enabling this option when running within VS Code:
parserOptions: {
projectService: {
loadTypeScriptPlugins: !!process.env.VSCODE_PID,
}
}
maximumDefaultProjectFileMatchCount_THIS_WILL_SLOW_DOWN_LINTING
默认:
8
。¥Default:
8
.
allowDefaultProject
可以匹配的最大文件数。每个文件匹配都会减慢 linting 的速度,因此如果你确实需要使用它,请在 typescript-eslint 上提交一个信息性问题,解释原因 - 因此我们可以帮助你避免使用它!
¥The maximum number of files allowDefaultProject
may match.
Each file match slows down linting, so if you do need to use this, please file an informative issue on typescript-eslint explaining why - so we can help you avoid using it!
projectFolderIgnoreList
默认
["**/node_modules/**"]
。¥Default
["**/node_modules/**"]
.
此选项允许你忽略文件夹包含在你提供的 project
列表中。如果你已配置通配符模式,但想要确保忽略某些文件夹,这非常有用。
¥This option allows you to ignore folders from being included in your provided list of project
s.
This is useful if you have configured glob patterns, but want to make sure you ignore certain folders.
它接受一个要从 project
全局中排除的全局数组。
¥It accepts an array of globs to exclude from the project
globs.
例如,默认情况下,它将确保像 ./**/tsconfig.json
这样的 glob 不会匹配你的 node_modules
文件夹中的任何 tsconfig
(一些 npm 包不会从其发布的包中排除它们的源文件)。
¥For example, by default it will ensure that a glob like ./**/tsconfig.json
will not match any tsconfig
s within your node_modules
folder (some npm packages do not exclude their source files from their published packages).
tsconfigRootDir
默认
undefined
。¥Default
undefined
.
此选项允许你提供上面 project
选项中指定的相对 TSConfig 路径的根目录。这样做可以确保从根目录以外的目录运行 ESLint 仍然能够找到你的 TSConfig。
¥This option allows you to provide the root directory for relative TSConfig paths specified in the project
option above.
Doing so ensures running ESLint from a directory other than the root will still be able to find your TSConfig.
warnOnUnsupportedTypeScriptVersion
默认
true
。¥Default
true
.
如果你使用未明确支持的 TypeScript 版本,此选项允许你切换解析器向你触发的警告。警告消息将如下所示:
¥This option allows you to toggle the warning that the parser will give you if you use a version of TypeScript which is not explicitly supported. The warning message would look like this:
=============
WARNING: You are currently running a version of TypeScript which is not officially supported by @typescript-eslint/typescript-estree.
* @typescript-eslint/typescript-estree version: 8.15.0
* Supported TypeScript versions: >=4.7.4 <5.7.0
* Your TypeScript version: 5.7.1
Please only submit bug reports when using the officially supported version.
=============
工具
¥Utilities
createProgram(configFile, projectDirectory)
这可作为 parserOptions.programs
功能用户从配置文件创建 TypeScript 程序实例的实用方法。
¥This serves as a utility method for users of the parserOptions.programs
feature to create a TypeScript program instance from a config file.
declare function createProgram(
configFile: string,
projectDirectory?: string,
): import('typescript').Program;
用法示例:
¥Example usage:
- 扁平配置
- 旧版配置
import * as parser from '@typescript-eslint/parser';
export default [
{
parserOptions: {
programs: [parser.createProgram('tsconfig.json')],
},
},
];
const parser = require('@typescript-eslint/parser');
module.exports = {
parserOptions: {
programs: [parser.createProgram('tsconfig.json')],
},
};
withoutProjectParserOptions(parserOptions)
删除提示解析器使用类型信息解析项目的选项。换句话说,如果你直接调用解析器,则可以使用它来确保一个文件将被单独解析,这样速度会快得多。
¥Removes options that prompt the parser to parse the project with type information. In other words, you can use this if you are invoking the parser directly, to ensure that one file will be parsed in isolation, which is much faster.
这在直接调用解析器的情况下很有用,例如在 ESLint 插件上下文中。
¥This is useful in cases where you invoke the parser directly, such as in an ESLint plugin context.
declare function withoutProjectParserOptions(
options: TSESTreeOptions,
): TSESTreeOptions;
用法 示例:
¥Example usage:
const parser = require('@typescript-eslint/parser');
function parse(path, content, context) {
const contextParserOptions = context.languageOptions?.parserOptions ?? {};
const parserOptions =
parser.withoutProjectParserOptions(contextParserOptions);
// Do something with the cleaned-up options eventually, such as invoking the parser
parser.parseForESLint(content, parserOptions);
}