UNPKG

12.7 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/master/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](../../docs/getting-started/linting/README.md)**
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/master/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/master/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```
72
73### `parserOptions.ecmaFeatures.jsx`
74
75Default `false`.
76
77Enable parsing JSX when `true`. More details can be found [here](https://www.typescriptlang.org/docs/handbook/jsx.html).
78
79**NOTE:** this setting does not affect known file types (`.js`, `.jsx`, `.ts`, `.tsx`, `.json`) because the TypeScript compiler has its own internal handling for known file extensions. The exact behavior is as follows:
80
81- if `parserOptions.project` is _not_ provided:
82 - `.js`, `.jsx`, `.tsx` files are parsed as if this is true.
83 - `.ts` files are parsed as if this is false.
84 - unknown extensions (`.md`, `.vue`) will respect this setting.
85- if `parserOptions.project` is provided (i.e. you are using rules with type information):
86 - `.js`, `.jsx`, `.tsx` files are parsed as if this is true.
87 - `.ts` files are parsed as if this is false.
88 - "unknown" extensions (`.md`, `.vue`) **are parsed as if this is false**.
89
90### `parserOptions.ecmaFeatures.globalReturn`
91
92Default `false`.
93
94This options allows you to tell the parser if you want to allow global `return` statements in your codebase.
95
96### `parserOptions.ecmaVersion`
97
98Default `2018`.
99
100Accepts any valid ECMAScript version number or `'latest'`:
101
102- A version: es3, es5, es6, es7, es8, es9, es10, es11, es12, es13, ..., or
103- A year: es2015, es2016, es2017, es2018, es2019, es2020, es2021, es2022, ..., or
104- `'latest'`
105
106When it's a version or a year, the value **must** be a number - so do not include the `es` prefix.
107
108Specifies 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
109
110### `parserOptions.jsxPragma`
111
112Default `'React'`
113
114The identifier that's used for JSX Elements creation (after transpilation).
115If 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`.
116
117This should not be a member expression - just the root identifier (i.e. use `"React"` instead of `"React.createElement"`).
118
119If you provide `parserOptions.project`, you do not need to set this, as it will automatically detected from the compiler.
120
121### `parserOptions.jsxFragmentName`
122
123Default `null`
124
125The identifier that's used for JSX fragment elements (after transpilation).
126If `null`, assumes transpilation will always use a member of the configured `jsxPragma`.
127This should not be a member expression - just the root identifier (i.e. use `"h"` instead of `"h.Fragment"`).
128
129If you provide `parserOptions.project`, you do not need to set this, as it will automatically detected from the compiler.
130
131### `parserOptions.lib`
132
133Default `['es2018']`
134
135For valid options, see the [TypeScript compiler options](https://www.typescriptlang.org/tsconfig#lib).
136
137Specifies 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.
138
139If you provide `parserOptions.project`, you do not need to set this, as it will automatically detected from the compiler.
140
141### `parserOptions.project`
142
143Default `undefined`.
144
145This 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`.
146
147- Accepted values:
148
149 ```js
150 // path
151 project: './tsconfig.json';
152
153 // glob pattern
154 project: './packages/**/tsconfig.json';
155
156 // array of paths and/or glob patterns
157 project: ['./packages/**/tsconfig.json', './separate-package/tsconfig.json'];
158 ```
159
160- 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.
161
162- 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.
163
164- 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:
165
166 ```jsonc
167 {
168 // extend your base config so you don't have to redefine your compilerOptions
169 "extends": "./tsconfig.json",
170 "include": [
171 "src/**/*.ts",
172 "test/**/*.ts",
173 "typings/**/*.ts",
174 // etc
175
176 // if you have a mixed JS/TS codebase, don't forget to include your JS files
177 "src/**/*.js"
178 ]
179 }
180 ```
181
182### `parserOptions.tsconfigRootDir`
183
184Default `undefined`.
185
186This option allows you to provide the root directory for relative tsconfig paths specified in the `project` option above.
187
188### `parserOptions.projectFolderIgnoreList`
189
190Default `["**/node_modules/**"]`.
191
192This option allows you to ignore folders from being included in your provided list of `project`s.
193This is useful if you have configured glob patterns, but want to make sure you ignore certain folders.
194
195It accepts an array of globs to exclude from the `project` globs.
196
197For 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).
198
199### `parserOptions.extraFileExtensions`
200
201Default `undefined`.
202
203This option allows you to provide one or more additional file extensions which should be considered in the TypeScript Program compilation.
204The default extensions are `.ts`, `.tsx`, `.js`, and `.jsx`. Add extensions starting with `.`, followed by the file extension. E.g. for a `.vue` file use `"extraFileExtensions: [".vue"]`.
205
206### `parserOptions.warnOnUnsupportedTypeScriptVersion`
207
208Default `true`.
209
210This 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
211
212### `parserOptions.createDefaultProgram`
213
214Default `false`.
215
216This 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.
217
218### `parserOptions.programs`
219
220Default `undefined`.
221
222This 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.
223This will override any programs that would have been computed from `parserOptions.project` or `parserOptions.createDefaultProgram`.
224All linted files must be part of the provided program(s).
225
226### `parserOptions.moduleResolver`
227
228Default `undefined`.
229
230This 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:
231
232```ts
233interface ModuleResolver {
234 version: 1;
235 resolveModuleNames(
236 moduleNames: string[],
237 containingFile: string,
238 reusedNames: string[] | undefined,
239 redirectedReference: ts.ResolvedProjectReference | undefined,
240 options: ts.CompilerOptions,
241 ): (ts.ResolvedModule | undefined)[];
242}
243```
244
245[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).
246
247Note 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).
248
249## Utilities
250
251### `createProgram(configFile, projectDirectory)`
252
253This serves as a utility method for users of the `parserOptions.programs` feature to create a TypeScript program instance from a config file.
254
255```ts
256declare function createProgram(
257 configFile: string,
258 projectDirectory?: string,
259): import('typescript').Program;
260```
261
262Example usage in .eslintrc.js:
263
264```js
265const parser = require('@typescript-eslint/parser');
266const programs = [parser.createProgram('tsconfig.json')];
267module.exports = {
268 parserOptions: {
269 programs,
270 },
271};
272```
273
274## Supported TypeScript Version
275
276Please see [`typescript-eslint`](https://github.com/typescript-eslint/typescript-eslint) for the supported TypeScript version.
277
278**Please ensure that you are using a supported version before submitting any issues/bug reports.**
279
280## Reporting Issues
281
282Please 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.
283
284## License
285
286TypeScript ESLint Parser is licensed under a permissive BSD 2-clause license.
287
288## Contributing
289
290[See the contributing guide here](../../CONTRIBUTING.md)