@typescript-eslint/typescript-estree
@typescript-eslint/parser
使用的底层代码将 TypeScript 源代码转换为与 ESTree 兼容的形式。✨¥The underlying code used by
@typescript-eslint/parser
that converts TypeScript source code into an ESTree-compatible form. ✨
该解析器被设计为通用且健壮的。它可用于支持任何需要获取 TypeScript 源代码并生成与 ESTree 兼容的 AST 的用例。
¥This parser is designed to be generic and robust. It can be used to power any use-case which requires taking TypeScript source code and producing an ESTree-compatible AST.
它最著名的是在这些超流行的开源项目中使用来增强其 TypeScript 支持:
¥It is most known for use within these hyper-popular open-source projects to power their TypeScript support:
-
ESLint,用于 JavaScript 和 JSX 的可插入式 linting 实用程序
¥ESLint, the pluggable linting utility for JavaScript and JSX
-
Prettier,一个有态度的代码格式化程序
¥Prettier, an opinionated code formatter
它的工作原理是:
¥It works by:
-
对给定源代码调用 TypeScript 编译器以生成 TypeScript AST
¥Invoking the TypeScript compiler on the given source code in order to produce a TypeScript AST
-
将 TypeScript AST 转换为 ESTree AST
¥Converting that TypeScript AST into an ESTree AST
API
解析
¥Parsing
parse(code, options)
使用提供的选项解析给定的代码字符串并返回与 ESTree 兼容的 AST。
¥Parses the given string of code with the options provided and returns an ESTree-compatible AST.
interface ParseOptions {
/**
* Specify the `sourceType`.
* For more details, see https://github.com/typescript-eslint/typescript-eslint/pull/9121
*/
sourceType?: SourceType;
/**
* Prevents the parser from throwing an error if it receives an invalid AST from TypeScript.
* This case only usually occurs when attempting to lint invalid code.
*/
allowInvalidAST?: boolean;
/**
* create a top-level comments array containing all comments
*/
comment?: boolean;
/**
* Whether deprecated AST properties should skip calling console.warn on accesses.
*/
suppressDeprecatedPropertyWarnings?: boolean;
/**
* An array of modules to turn explicit debugging on for.
* - 'typescript-eslint' is the same as setting the env var `DEBUG=typescript-eslint:*`
* - 'eslint' is the same as setting the env var `DEBUG=eslint:*`
* - 'typescript' is the same as setting `extendedDiagnostics: true` in your tsconfig compilerOptions
* * For convenience, also supports a boolean:
* - true === ['typescript-eslint']
* - false === []
*/
debugLevel?: boolean | ('typescript-eslint' | 'eslint' | 'typescript')[];
/**
* Cause the parser to error if it encounters an unknown AST node type (useful for testing).
* This case only usually occurs when TypeScript releases new features.
*/
errorOnUnknownASTType?: boolean;
/**
* Absolute (or relative to `cwd`) path to the file being parsed.
*/
filePath?: string;
/**
* 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'` - parse all JSDoc comments, always.
* - `'none'` - parse no JSDoc comments, ever.
* - `'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.
* * If you do not rely on JSDoc tags from the TypeScript AST, then you can safely set this to `'none'` to improve performance.
*/
jsDocParsingMode?: JSDocParsingMode;
/**
* Enable parsing of JSX.
* For more details, see https://ts.nodejs.cn/docs/handbook/jsx.html
* * NOTE: this setting does not effect known file types (.js, .cjs, .mjs, .jsx, .ts, .mts, .cts, .tsx, .json) because the
* TypeScript compiler has its own internal handling for known file extensions.
* * For the exact behavior, see https://github.com/typescript-eslint/typescript-eslint/tree/main/packages/parser#parseroptionsecmafeaturesjsx
*/
jsx?: boolean;
/**
* Controls whether the `loc` information to each node.
* The `loc` property is an object which contains the exact line/column the node starts/ends on.
* This is similar to the `range` property, except it is line/column relative.
*/
loc?: boolean;
/*
* Allows overriding of function used for logging.
* When value is `false`, no logging will occur.
* When value is not provided, `console.log()` will be used.
*/
loggerFn?: Function | false;
/**
* Controls whether the `range` property is included on AST nodes.
* The `range` property is a [number, number] which indicates the start/end index of the node in the file contents.
* This is similar to the `loc` property, except this is the absolute index.
*/
range?: boolean;
/**
* Set to true to create a top-level array containing all tokens from the file.
*/
tokens?: boolean;
}
const PARSE_DEFAULT_OPTIONS: ParseOptions = {
comment: false,
filePath: 'estree.ts', // or 'estree.tsx', if you pass jsx: true
jsDocParsingMode: 'all',
jsx: false,
loc: false,
loggerFn: undefined,
range: false,
tokens: false,
};
declare function parse(
code: string,
options: ParseOptions = PARSE_DEFAULT_OPTIONS,
): TSESTree.Program;
用法示例:
¥Example usage:
import { parse } from '@typescript-eslint/typescript-estree';
const code = `const hello: string = 'world';`;
const ast = parse(code, {
loc: true,
range: true,
});
parseAndGenerateServices(code, options)
使用提供的选项解析给定的代码字符串并返回与 ESTree 兼容的 AST。接受可用于与 AST 一起生成类型信息的附加选项。
¥Parses the given string of code with the options provided and returns an ESTree-compatible AST. Accepts additional options which can be used to generate type information along with the AST.
interface ParseAndGenerateServicesOptions extends ParseOptions {
/**
* Granular control of the expiry lifetime of our internal caches.
* You can specify the number of seconds as an integer number, or the string
* 'Infinity' if you never want the cache to expire.
* * By default cache entries will be evicted after 30 seconds, or will persist
* indefinitely if `disallowAutomaticSingleRunInference = false` AND the parser
* infers that it is a single run.
*/
cacheLifetime?: {
/**
* Glob resolution for `parserOptions.project` values.
*/
glob?: number | 'Infinity';
};
/**
* ESLint (and therefore typescript-eslint) is used in both "single run"/one-time contexts,
* such as an ESLint CLI invocation, and long-running sessions (such as continuous feedback
* on a file in an IDE).
* * When typescript-eslint handles TypeScript Program management behind the scenes, this distinction
* is important because there is significant overhead to managing the so called Watch Programs
* needed for the long-running use-case.
* * By default, we will use common heuristics to infer whether ESLint is being
* used as part of a single run. This option disables those heuristics, and
* therefore the performance optimizations gained by them.
* * In other words, typescript-eslint is faster by default, and this option
* disables an automatic performance optimization.
* * This setting's default value can be specified by setting a `TSESTREE_SINGLE_RUN`
* environment variable to `"false"` or `"true"`.
* Otherwise, the default value is `false`.
*/
disallowAutomaticSingleRunInference?: boolean;
/**
* Causes the parser to error if the TypeScript compiler returns any unexpected syntax/semantic errors.
*/
errorOnTypeScriptSyntacticAndSemanticIssues?: boolean;
/**
* When `project` is provided, this controls the non-standard file extensions which will be parsed.
* It accepts an array of file extensions, each preceded by a `.`.
* * NOTE: When used with {@link projectService}, full project reloads may occur.
*/
extraFileExtensions?: string[];
/**
* Absolute (or relative to `tsconfigRootDir`) path to the file being parsed.
* When `project` is provided, this is required, as it is used to fetch the file from the TypeScript compiler's cache.
*/
filePath?: string;
/**
* Allows the user to control whether or not two-way AST node maps are preserved
* during the AST conversion process.
* * By default: the AST node maps are NOT preserved, unless `project` has been specified,
* in which case the maps are made available on the returned `parserServices`.
* * NOTE: If `preserveNodeMaps` is explicitly set by the user, it will be respected,
* regardless of whether or not `project` is in use.
*/
preserveNodeMaps?: boolean;
/**
* Absolute (or relative to `tsconfigRootDir`) paths to the tsconfig(s),
* or `true` to find the nearest tsconfig.json to the file.
* If this is provided, type information will be returned.
* * If set to `false`, `null`, or `undefined`, type information will not be returned.
* * Note that {@link projectService} is now preferred.
*/
project?: string[] | string | boolean | null;
/**
* If you provide a glob (or globs) to the project option, you can use this option to ignore certain folders from
* being matched by the globs.
* This accepts an array of globs to ignore.
* * By default, this is set to ["/node_modules/"]
*/
projectFolderIgnoreList?: string[];
/**
* Whether to create a shared TypeScript project service to power program creation.
*/
projectService?: boolean | ProjectServiceOptions;
/**
* The absolute path to the root directory for all provided `project`s.
*/
tsconfigRootDir?: string;
/**
* An array of one or more instances of TypeScript Program objects to be used for type information.
* This overrides any program or programs that would have been computed from the `project` option.
* All linted files must be part of the provided program(s).
*/
programs?: Program[];
}
/**
* Granular options to configure the project service.
*/
interface ProjectServiceOptions {
/**
* Globs of files to allow running with the default project compiler options.
*/
allowDefaultProject?: string[];
/**
* Path to a TSConfig to use instead of TypeScript's default project configuration.
* @default 'tsconfig.json'
*/
defaultProject?: string;
/**
* Whether to load TypeScript plugins as configured in the TSConfig.
*/
loadTypeScriptPlugins?: boolean;
/**
* The maximum number of files {@link 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!
* @default 8
*/
maximumDefaultProjectFileMatchCount_THIS_WILL_SLOW_DOWN_LINTING?: number;
}
interface ParserServices {
program: ts.Program;
esTreeNodeToTSNodeMap: WeakMap<TSESTree.Node, ts.Node | ts.Token>;
tsNodeToESTreeNodeMap: WeakMap<ts.Node | ts.Token, TSESTree.Node>;
}
interface ParseAndGenerateServicesResult<T extends TSESTreeOptions> {
ast: TSESTree.Program;
services: ParserServices;
}
const PARSE_AND_GENERATE_SERVICES_DEFAULT_OPTIONS: ParseOptions = {
...PARSE_DEFAULT_OPTIONS,
errorOnTypeScriptSyntacticAndSemanticIssues: false,
extraFileExtensions: [],
preserveNodeMaps: false, // or true, if you do not set this, but pass `project`
project: undefined,
projectFolderIgnoreList: ['/node_modules/'],
tsconfigRootDir: process.cwd(),
};
declare function parseAndGenerateServices(
code: string,
options: ParseOptions = PARSE_DEFAULT_OPTIONS,
): ParseAndGenerateServicesResult;
用法示例:
¥Example usage:
import { parseAndGenerateServices } from '@typescript-eslint/typescript-estree';
const code = `const hello: string = 'world';`;
const { ast, services } = parseAndGenerateServices(code, {
filePath: '/some/path/to/file/foo.ts',
loc: true,
project: './tsconfig.json',
range: true,
});
TSESTree
、AST_NODE_TYPES
和 AST_TOKEN_TYPES
¥TSESTree
, AST_NODE_TYPES
and AST_TOKEN_TYPES
解析函数生成的 AST 的类型。
¥Types for the AST produced by the parse functions.
-
TSESTree
是一个命名空间,其中包含表示解析器生成的所有 AST 节点的对象类型。¥
TSESTree
is a namespace which contains object types representing all of the AST Nodes produced by the parser. -
AST_NODE_TYPES
是一个枚举,它为每个 AST 节点的type
属性提供值。¥
AST_NODE_TYPES
is an enum which provides the values for every single AST node'stype
property. -
AST_TOKEN_TYPES
是一个枚举,它为每个 AST 标记的type
属性提供值。¥
AST_TOKEN_TYPES
is an enum which provides the values for every single AST token'stype
property.
工具
¥Utilities
createProgram(configFile, projectDirectory)
这可作为 ParseOptions.programs
功能用户从配置文件创建 TypeScript 程序实例的实用方法。
¥This serves as a utility method for users of the ParseOptions.programs
feature to create a TypeScript program instance from a config file.
declare function createProgram(
configFile: string,
projectDirectory: string = process.cwd(),
): import('typescript').Program;
用法示例:
¥Example usage:
const tsESTree = require('@typescript-eslint/typescript-estree');
const program = tsESTree.createProgram('tsconfig.json');
const code = `const hello: string = 'world';`;
const { ast, services } = parseAndGenerateServices(code, {
filePath: '/some/path/to/file/foo.ts',
loc: true,
program,
range: true,
});
调试
¥Debugging
如果你遇到要调查的解析器错误,你可以通过设置环境变量来打开调试日志记录:DEBUG=typescript-eslint:*
。即在此 repo 中,你可以运行:DEBUG=typescript-eslint:* yarn lint
。
¥If you encounter a bug with the parser that you want to investigate, you can turn on the debug logging via setting the environment variable: DEBUG=typescript-eslint:*
.
I.e. in this repo you can run: DEBUG=typescript-eslint:* yarn lint
.
这将包括 TypeScript 服务器日志。要关闭这些日志,请在设置环境变量时包含 -typescript-eslint:typescript-estree:tsserver:*
。即对于此 repo 更改为:DEBUG='typescript-eslint:*,-typescript-eslint:typescript-estree:tsserver:*' yarn lint
。
¥This will include TypeScript server logs.
To turn off these logs, include -typescript-eslint:typescript-estree:tsserver:*
when setting the environment variable.
I.e. for this repo change to: DEBUG='typescript-eslint:*,-typescript-eslint:typescript-estree:tsserver:*' yarn lint
.