Skip to main content

parser


@typescript-eslint/parser

ESLint 解析器 用于将 TypeScript 代码解析为 ESLint 兼容节点,并提供支持 TypeScript 程序。 ✨

这是必要的,因为 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

配置

通过在 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';
};
ecmaFeatures?: {
jsx?: boolean;
globalReturn?: boolean;
};
ecmaVersion?: number | 'latest';
emitDecoratorMetadata?: boolean;
extraFileExtensions?: string[];
jsDocParsingMode?: 'all' | 'none' | 'type-info';
jsxFragmentName?: string | null;
jsxPragma?: string | null;
lib?: string[];
programs?: import('typescript').Program;
project?: string | string[] | true;
projectFolderIgnoreList?: string[];
tsconfigRootDir?: string;
warnOnUnsupportedTypeScriptVersion?: boolean;
}

cacheLifetime

此选项允许你精细地控制我们的内部缓存过期长度。

英:This option allows you to granularly control our internal cache expiry lengths.

你可以将秒数指定为整数,如果你不想让缓存过期,则可以指定字符串 'Infinity'。

英:You can specify the number of seconds as an integer number, or the string 'Infinity' if you never want the cache to expire.

默认情况下,缓存条目将在 30 秒后被逐出,或者如果解析器推断它是单次运行,则将无限期地保留。

英:By default cache entries will be evicted after 30 seconds, or will persist indefinitely if the parser infers that it is a single run.

ecmaFeatures

用于描述如何解析原始语法的可选附加选项。

英:Optional additional options to describe how to parse the raw syntax.

jsx

默认 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
  • .ts.mts.cts 文件始终被解析为 false
  • 对于 "unknown" 分机(.md.vue):
    • 如果未提供 parserOptions.project
      • 该设置将受到尊重。
    • 如果提供了 parserOptions.project(即你正在使用带有类型信息的规则):
      • 总是被解析为好像这是 false

globalReturn

默认 false

此选项允许你告诉解析器是否要在代码库中允许全局 return 语句。

英:This options allows you to tell the parser if you want to allow global return statements in your codebase.

ecmaVersion

默认 2018

接受任何有效的 ECMAScript 版本号或 'latest'

英:Accepts any valid ECMAScript version number or 'latest':

  • 厌恶: es3、es5、es6、es7、es8、es9、es10、es11、es12、es13、...或
  • 一年: es2015、es2016、es2017、es2018、es2019、es2020、es2021、es2022,...,或
  • 'latest'

当它是版本或年份时,值 must 是一个数字 - 因此不要包含 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

此选项允许你告诉解析器就像在 tsconfig.json 中设置了 emitDecoratorMetadata: true,但没有设置 类型感知的 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.

extraFileExtensions

默认 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"].

jsDocParsingMode

默认如果设置了 parserOptions.project,则设置 'all',否则设置 '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 注释。
  • 'none' - 永远不解析 JSDoc 注释。
  • 'type-info' - 仅解析提供正确类型信息所需的 JSDoc 注释。 TS 总是会解析非 TS 文件中的 JSDoc,但绝不会解析 TS 文件中的 JSDoc。

如果你不使用像 eslint-plugin-deprecation 这样依赖于 TS 的 JSDoc 标记表示的 lint 规则,那么你可以将其设置为 '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

用于 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 automatically detected from the compiler.

jsxPragma

默认 '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 automatically detected from the compiler.

lib

默认 ['es2018']

有关有效选项,请参阅 TypeScript 编译器选项

英:For valid options, see the TypeScript compiler options.

指定可用的 TypeScript lib。 范围分析器使用它来确保为 TypeScript 公开的类型声明了全局变量。

英:Specifies the TypeScript libs 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 automatically detected from the compiler.

programs

默认 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

默认 undefined

此选项允许你提供项目 tsconfig.json 的路径。 如果你想使用需要类型信息的规则,则需要此设置。 如果未设置 tsconfigRootDir,相对路径将相对于当前工作目录进行解释。 如果你打算从项目根目录以外的目录运行 ESLint,则应考虑使用 tsconfigRootDir

英:This option allows you to provide a path to your project's tsconfig.json. This setting is required if you want to use rules which require type information. Relative paths are interpreted relative to the current working directory if tsconfigRootDir is not set. If you intend on running ESLint from directories other than the project root, you should consider using tsconfigRootDir.

  • 接受的值:

    // find the tsconfig.json nearest 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'];
  • 如果是 true,每个源文件的解析将找到距离该源文件最近的 tsconfig.json 文件。

    • 这是通过检查源文件的目录树中最近的 tsconfig.json 来完成的。
  • 如果你使用项目引用,TypeScript 将不会自动使用项目引用来解析文件。 这意味着你必须单独或通过 glob 将每个引用的 tsconfig 添加到 project 字段。

  • 请注意,在 parserOptions.project 中使用宽 glob ** 可能会导致性能影响。 与使用 ** 递归检查所有文件夹的 glob 不同,更喜欢一次使用单个 * 的路径。 欲了解更多信息,请参阅 #2611

  • TypeScript 将忽略同一文件夹中具有重复文件名的文件(例如 src/file.tssrc/file.js)。 TypeScript 故意忽略除其中一个文件之外的所有文件,仅保留具有最高优先级扩展名的一个文件(扩展名优先级顺序(从最高到最低)为 .ts.tsx.d.ts.js.jsx)。 有关更多信息,请参阅#955。

  • 请注意,如果指定了此设置,则必须仅对项目中包含的文件(如所提供的 tsconfig.json 文件定义)进行 lint 检查。 如果你现有的配置不包含你想要检查的所有文件,你可以创建一个单独的 tsconfig.eslint.json,如下所示:

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

projectFolderIgnoreList

默认 ["**/node_modules/**"]

此选项允许你忽略包含在你提供的 project 列表中的文件夹。 如果你已配置通配符模式,但想要确保忽略某些文件夹,这非常有用。

英:This option allows you to ignore folders from being included in your provided list of projects. 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 tsconfigs within your node_modules folder (some npm packages do not exclude their source files from their published packages).

tsconfigRootDir

默认 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

如果你使用未明确支持的 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.

You may find that it works just fine, or you may not.

SUPPORTED TYPESCRIPT VERSIONS: >=3.3.1 <5.1.0

YOUR TYPESCRIPT VERSION: 5.1.3

Please only submit bug reports when using the officially supported version.

=============

EXPERIMENTAL_useProjectService

parserOptions.project 的实验性替代品。 这指示解析器使用更加无缝的 TypeScript API 来生成规则的类型信息。 它将自动检测每个文件的 TSConfig(如 project: true),并且还允许在没有 allowJs 编译器选项的情况下计算 JavaScript 文件的类型信息(与 project: true 不同)。

英:An experimental alternative to parserOptions.project. This directs the parser to use a more seamless TypeScript API to generate type information for rules. It will automatically detect the TSConfig for each file (like project: true), and will also allow type information to be computed for JavaScript files without the allowJs compiler option (unlike project: true).

module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
EXPERIMENTAL_useProjectService: true,
},
};

这个选项应该带来两个主要好处:

英:This option should bring two main benefits:

  • 更简单的配置: 大多数项目不需要显式配置 project 路径或创建 tsconfig.eslint.json
  • 改进的性能: 该 API 在 TypeScript 端进行了速度优化
    • 该选项的初始版本展示了 typescript-eslint monorepo 子集的性能变化,从慢 11% 到快 70%

我们希望此选项最终将成为启用类型化 linting 的标准方法。 它将解析器从手动创建 TypeScript 程序切换为调用 VS Code 等编辑器使用的相同 "项目服务" API。 但是,由于它太新且未经测试,因此我们至少在所有 6.X 版本中将其保留在 EXPERIMENTAL_ 前缀下。

英:We're hopeful this option will eventually become the standard way to enable typed linting. It switches the parser from manually creating TypeScript programs to instead calling the same "project services" API used by editors such as VS Code. However, because it's so new and untested, we're keeping it under the EXPERIMENTAL_ prefix for at least all of the 6.X versions.

请参阅 feat(typescript-estree): add EXPERIMENTAL_useProjectService option to use TypeScript project service 了解更多信息。

英:See feat(typescript-estree): add EXPERIMENTAL_useProjectService option to use TypeScript project service for more information.

工具

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:

.eslintrc.js
const parser = require('@typescript-eslint/parser');

module.exports = {
parserOptions: {
programs: [parser.createProgram('tsconfig.json')],
},
};