UNPKG

13.3 kBMarkdownView Raw
1<h1 align="center">TypeScript ESLint Parser</h1>
2
3<p align="center">An ESLint parser which leverages <a href="https://github.com/typescript-eslint/typescript-eslint/tree/main/packages/typescript-estree">TypeScript ESTree</a> to allow for ESLint to lint TypeScript source code.</p>
4
5<p align="center">
6 <img src="https://github.com/typescript-eslint/typescript-eslint/workflows/CI/badge.svg" alt="CI" />
7 <a href="https://www.npmjs.com/package/@typescript-eslint/parser"><img src="https://img.shields.io/npm/v/@typescript-eslint/parser.svg?style=flat-square" alt="NPM Version" /></a>
8 <a href="https://www.npmjs.com/package/@typescript-eslint/parser"><img src="https://img.shields.io/npm/dm/@typescript-eslint/parser.svg?style=flat-square" alt="NPM Downloads" /></a>
9</p>
10
11## Getting Started
12
13**[You can find our Getting Started docs here](https://typescript-eslint.io/docs/linting)**
14
15These docs walk you through setting up ESLint, this parser, and our plugin. If you know what you're doing and just want to quick start, read on...
16
17## Quick-start
18
19### Installation
20
21```bash
22$ yarn add -D typescript @typescript-eslint/parser
23$ npm i --save-dev typescript @typescript-eslint/parser
24```
25
26### Usage
27
28In your ESLint configuration file, set the `parser` property:
29
30```json
31{
32 "parser": "@typescript-eslint/parser"
33}
34```
35
36There is sometimes an incorrect assumption that the parser itself is what does everything necessary to facilitate the use of ESLint with TypeScript. In actuality, it is the combination of the parser _and_ one or more plugins which allow you to maximize your usage of ESLint with TypeScript.
37
38For example, once this parser successfully produces an AST for the TypeScript source code, it might well contain some information which simply does not exist in a standard JavaScript context, such as the data for a TypeScript-specific construct, like an `interface`.
39
40The core rules built into ESLint, such as `indent` have no knowledge of such constructs, so it is impossible to expect them to work out of the box with them.
41
42Instead, you also need to make use of one more plugins which will add or extend rules with TypeScript-specific features.
43
44By far the most common case will be installing the [`@typescript-eslint/eslint-plugin`](https://github.com/typescript-eslint/typescript-eslint/tree/main/packages/eslint-plugin) plugin, but there are also other relevant options available such a [`@typescript-eslint/eslint-plugin-tslint`](https://github.com/typescript-eslint/typescript-eslint/tree/main/packages/eslint-plugin-tslint).
45
46## Configuration
47
48The following additional configuration options are available by specifying them in [`parserOptions`](https://eslint.org/docs/user-guide/configuring/language-options#specifying-parser-options) in your ESLint configuration file.
49
50```ts
51interface ParserOptions {
52 ecmaFeatures?: {
53 jsx?: boolean;
54 globalReturn?: boolean;
55 };
56 ecmaVersion?: number | 'latest';
57
58 jsxPragma?: string | null;
59 jsxFragmentName?: string | null;
60 lib?: string[];
61
62 project?: string | string[];
63 projectFolderIgnoreList?: string[];
64 tsconfigRootDir?: string;
65 extraFileExtensions?: string[];
66 warnOnUnsupportedTypeScriptVersion?: boolean;
67
68 program?: import('typescript').Program;
69 moduleResolver?: string;
70
71 emitDecoratorMetadata?: boolean;
72}
73```
74
75### `parserOptions.ecmaFeatures.jsx`
76
77Default `false`.
78
79Enable parsing JSX when `true`. More details can be found [here](https://www.typescriptlang.org/docs/handbook/jsx.html).
80
81**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.
82
83<!-- https://github.com/microsoft/TypeScript/blob/d6e483b8dabd8fd37c00954c3f2184bb7f1eb90c/src/compiler/utilities.ts#L6281-L6285 -->
84
85The exact behavior is as follows:
86
87- `.js`, `.mjs`, `.cjs`, `.jsx`, `.tsx` files are always parsed as if this is `true`.
88- `.ts`, `.mts`, `.cts` files are always parsed as if this is `false`.
89- For "unknown" extensions (`.md`, `.vue`):
90 - If `parserOptions.project` is _not_ provided:
91 - The setting will be respected.
92 - If `parserOptions.project` is provided (i.e. you are using rules with type information):
93 - **always parsed as if this is `false`**
94
95### `parserOptions.ecmaFeatures.globalReturn`
96
97Default `false`.
98
99This options allows you to tell the parser if you want to allow global `return` statements in your codebase.
100
101### `parserOptions.ecmaVersion`
102
103Default `2018`.
104
105Accepts any valid ECMAScript version number or `'latest'`:
106
107- A version: es3, es5, es6, es7, es8, es9, es10, es11, es12, es13, ..., or
108- A year: es2015, es2016, es2017, es2018, es2019, es2020, es2021, es2022, ..., or
109- `'latest'`
110
111When it's a version or a year, the value **must** be a number - so do not include the `es` prefix.
112
113Specifies 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
114
115### `parserOptions.jsxPragma`
116
117Default `'React'`
118
119The identifier that's used for JSX Elements creation (after transpilation).
120If you're using a library other than React (like `preact`), then you should change this value. If you are using the [new JSX transform](https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html) you can set this to `null`.
121
122This should not be a member expression - just the root identifier (i.e. use `"React"` instead of `"React.createElement"`).
123
124If you provide `parserOptions.project`, you do not need to set this, as it will automatically detected from the compiler.
125
126### `parserOptions.jsxFragmentName`
127
128Default `null`
129
130The identifier that's used for JSX fragment elements (after transpilation).
131If `null`, assumes transpilation will always use a member of the configured `jsxPragma`.
132This should not be a member expression - just the root identifier (i.e. use `"h"` instead of `"h.Fragment"`).
133
134If you provide `parserOptions.project`, you do not need to set this, as it will automatically detected from the compiler.
135
136### `parserOptions.lib`
137
138Default `['es2018']`
139
140For valid options, see the [TypeScript compiler options](https://www.typescriptlang.org/tsconfig#lib).
141
142Specifies 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.
143
144If you provide `parserOptions.project`, you do not need to set this, as it will automatically detected from the compiler.
145
146### `parserOptions.project`
147
148Default `undefined`.
149
150This 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`.
151
152- Accepted values:
153
154 ```js
155 // path
156 project: './tsconfig.json';
157
158 // glob pattern
159 project: './packages/**/tsconfig.json';
160
161 // array of paths and/or glob patterns
162 project: ['./packages/**/tsconfig.json', './separate-package/tsconfig.json'];
163 ```
164
165- 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.
166
167- TypeScript will ignore files with duplicate filenames in the same folder (for example, `src/file.ts` and `src/file.js`). TypeScript purposely ignore 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.
168
169- Note that if this setting is specified and `createDefaultProgram` is not, you must only lint files that are included in the projects as defined by the provided `tsconfig.json` files. 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:
170
171 ```jsonc
172 {
173 // extend your base config so you don't have to redefine your compilerOptions
174 "extends": "./tsconfig.json",
175 "include": [
176 "src/**/*.ts",
177 "test/**/*.ts",
178 "typings/**/*.ts",
179 // etc
180
181 // if you have a mixed JS/TS codebase, don't forget to include your JS files
182 "src/**/*.js"
183 ]
184 }
185 ```
186
187### `parserOptions.tsconfigRootDir`
188
189Default `undefined`.
190
191This option allows you to provide the root directory for relative tsconfig paths specified in the `project` option above.
192
193### `parserOptions.projectFolderIgnoreList`
194
195Default `["**/node_modules/**"]`.
196
197This option allows you to ignore folders from being included in your provided list of `project`s.
198This is useful if you have configured glob patterns, but want to make sure you ignore certain folders.
199
200It accepts an array of globs to exclude from the `project` globs.
201
202For 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).
203
204### `parserOptions.extraFileExtensions`
205
206Default `undefined`.
207
208This option allows you to provide one or more additional file extensions which should be considered in the TypeScript Program compilation.
209The default extensions are `['.js', '.mjs', '.cjs', '.jsx', '.ts', '.mts', '.cts', '.tsx']`.
210Add extensions starting with `.`, followed by the file extension. E.g. for a `.vue` file use `"extraFileExtensions": [".vue"]`.
211
212### `parserOptions.warnOnUnsupportedTypeScriptVersion`
213
214Default `true`.
215
216This 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
217
218### `parserOptions.createDefaultProgram`
219
220Default `false`.
221
222This option allows you to request that when the `project` setting is specified, files will be allowed when not included in the projects defined by the provided `tsconfig.json` files. **Using this option will incur significant performance costs. This option is primarily included for backwards-compatibility.** See the **`project`** section above for more information.
223
224### `parserOptions.programs`
225
226Default `undefined`.
227
228This option allows you to programmatically provide an array of one or more instances of a TypeScript Program object that will provide type information to rules.
229This will override any programs that would have been computed from `parserOptions.project` or `parserOptions.createDefaultProgram`.
230All linted files must be part of the provided program(s).
231
232### `parserOptions.moduleResolver`
233
234Default `undefined`.
235
236This option allows you to provide a custom module resolution. The value should point to a JS file that default exports (`export default`, or `module.exports =`, or `export =`) a file with the following interface:
237
238```ts
239interface ModuleResolver {
240 version: 1;
241 resolveModuleNames(
242 moduleNames: string[],
243 containingFile: string,
244 reusedNames: string[] | undefined,
245 redirectedReference: ts.ResolvedProjectReference | undefined,
246 options: ts.CompilerOptions,
247 ): (ts.ResolvedModule | undefined)[];
248}
249```
250
251[Refer to the TypeScript Wiki for an example on how to write the `resolveModuleNames` function](https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API#customizing-module-resolution).
252
253Note that if you pass custom programs via `options.programs` this option will not have any effect over them (you can simply add the custom resolution on them directly).
254
255### `parserOptions.emitDecoratorMetadata`
256
257Default `undefined`.
258
259This option allow you to tell parser to act as if `emitDecoratorMetadata: true` is set in `tsconfig.json`, but without [type-aware linting](https://typescript-eslint.io/docs/linting/type-linting). In other words, you don't have to specify `parserOptions.project` in this case, making the linting process faster.
260
261## Utilities
262
263### `createProgram(configFile, projectDirectory)`
264
265This serves as a utility method for users of the `parserOptions.programs` feature to create a TypeScript program instance from a config file.
266
267```ts
268declare function createProgram(
269 configFile: string,
270 projectDirectory?: string,
271): import('typescript').Program;
272```
273
274Example usage in .eslintrc.js:
275
276```js
277const parser = require('@typescript-eslint/parser');
278const programs = [parser.createProgram('tsconfig.json')];
279module.exports = {
280 parserOptions: {
281 programs,
282 },
283};
284```
285
286## Supported TypeScript Version
287
288Please see [`typescript-eslint`](https://github.com/typescript-eslint/typescript-eslint) for the supported TypeScript version.
289
290**Please ensure that you are using a supported version before submitting any issues/bug reports.**
291
292## Reporting Issues
293
294Please use the `@typescript-eslint/parser` issue template when creating your issue and fill out the information requested as best you can. This will really help us when looking into your issue.
295
296## License
297
298TypeScript ESLint Parser is licensed under a permissive BSD 2-clause license.
299
300## Contributing
301
302[See the contributing guide here](../../CONTRIBUTING.md)