1 | [![NPM version](https://badge.fury.io/js/tslint.svg)](http://badge.fury.io/js/tslint)
|
2 | [![Downloads](http://img.shields.io/npm/dm/tslint.svg)](https://npmjs.org/package/tslint)
|
3 | [![Circle CI](https://circleci.com/gh/palantir/tslint.svg?style=svg)](https://circleci.com/gh/palantir/tslint)
|
4 | [![Join the chat at https://gitter.im/palantir/tslint](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/palantir/tslint?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
5 |
|
6 | TSLint
|
7 | ======
|
8 |
|
9 | An extensible linter for the [TypeScript language](https://github.com/Microsoft/TypeScript).
|
10 |
|
11 | TSLint supports:
|
12 |
|
13 | - custom lint rules
|
14 | - custom formatters (failure reporters)
|
15 | - inline disabling / enabling of rules
|
16 | - configuration presets (`tslint:latest`, `tslint-react`, etc.) & composition
|
17 | - automatic fixing of formatting & style violations
|
18 | - integration with [msbuild](https://github.com/joshuakgoldberg/tslint.msbuild), [grunt](https://github.com/palantir/grunt-tslint), [gulp](https://github.com/panuhorsmalahti/gulp-tslint), [atom](https://github.com/AtomLinter/linter-tslint), [eclipse](https://github.com/palantir/eclipse-tslint), [emacs](http://flycheck.org), [sublime](https://packagecontrol.io/packages/SublimeLinter-contrib-tslint), [vim](https://github.com/scrooloose/syntastic), [visual studio](https://visualstudiogallery.msdn.microsoft.com/6edc26d4-47d8-4987-82ee-7c820d79be1d), [vscode](https://marketplace.visualstudio.com/items?itemName=eg2.tslint), [webstorm](https://www.jetbrains.com/webstorm/help/tslint.html), and more
|
19 |
|
20 | Table of Contents
|
21 | ------------
|
22 |
|
23 | - [Installation](#installation)
|
24 | - [Usage](#usage)
|
25 | - [Core Rules](#core-rules)
|
26 | - [Core Formatters](#core-formatters)
|
27 | - [Rule Flags](#rule-flags)
|
28 | - [Custom Rules](#custom-rules)
|
29 | - [Development](#development)
|
30 | - [Creating a new release](#creating-a-new-release)
|
31 |
|
32 |
|
33 | Installation
|
34 | ------------
|
35 | <sup>[back to ToC ↑](#table-of-contents)</sup>
|
36 |
|
37 | #### CLI
|
38 |
|
39 | ```
|
40 | npm install -g tslint typescript
|
41 | ```
|
42 |
|
43 | #### Library
|
44 |
|
45 | ```
|
46 | npm install tslint typescript
|
47 | ```
|
48 |
|
49 | #### Peer dependencies
|
50 |
|
51 | `typescript` is a peer dependency of `tslint`. This allows you to update the compiler independently from the
|
52 | linter. This also means that `tslint` will have to use the same version of `tsc` used to actually compile your sources.
|
53 |
|
54 | Breaking changes in the latest dev release of `typescript@next` might break something in the linter if we haven't built against that release yet. If this happens to you, you can try:
|
55 |
|
56 | 1. picking up `tslint@next`, which may have some bugfixes not released in `tslint@latest`
|
57 | (see [release notes here](https://github.com/palantir/tslint/releases)).
|
58 | 2. rolling back `typescript` to a known working version.
|
59 |
|
60 | Usage
|
61 | -----
|
62 | <sup>[back to ToC ↑](#table-of-contents)</sup>
|
63 |
|
64 | Please ensure that the TypeScript source files compile correctly _before_ running the linter.
|
65 |
|
66 | #### Configuration
|
67 |
|
68 | TSLint is configured via a file named `tslint.json`. This file is loaded from the current path, or the user's home directory, in that order.
|
69 |
|
70 | The configuration file specifies which rules are enabled and their options. These configurations may _extend_ other ones via the `"extends"` field in `tslint.json`.
|
71 |
|
72 | ```js
|
73 | {
|
74 | /*
|
75 | * Possible values:
|
76 | * - the name of a built-in config
|
77 | * - the name of an NPM module which has a "main" file that exports a config object
|
78 | * - a relative path to a JSON file
|
79 | */
|
80 | "extends": "tslint:latest",
|
81 | "rules": {
|
82 | /*
|
83 | * Any rules specified here will override those from the base config we are extending.
|
84 | */
|
85 | "curly": true
|
86 | },
|
87 | "jsRules": {
|
88 | /*
|
89 | * Any rules specified here will override those from the base config we are extending.
|
90 | */
|
91 | "curly": true
|
92 | },
|
93 | "rulesDirectory": [
|
94 | /*
|
95 | * A list of relative or absolute paths to directories that contain custom rules.
|
96 | * See the Custom Rules documentation below for more details.
|
97 | */
|
98 | ]
|
99 | }
|
100 | ```
|
101 |
|
102 | Built-in configs include `tslint:latest` and `tslint:recommended`. You may inspect their source [here](https://github.com/palantir/tslint/tree/master/src/configs).
|
103 |
|
104 | __`tslint:recommended`__ is a stable, somewhat opinionated set of rules which we encourage for general TypeScript programming. This configuration follows semver, so it will _not_ have breaking changes across minor or patch releases.
|
105 |
|
106 | __`tslint:latest`__ extends `tslint:recommended` and is continuously updated to include configuration for the latest rules in every TSLint release. Using this config may introduce breaking changes across minor releases as new rules are enabled which cause lint failures in your code. When TSLint reaches a major version bump, `tslint:recommended` will be updated to be identical to `tslint:latest`.
|
107 |
|
108 | See the [core rules list](#core-rules) below for descriptions of all the rules.
|
109 |
|
110 | #### CLI
|
111 |
|
112 | usage: `tslint [options] file ...`
|
113 |
|
114 | Options:
|
115 |
|
116 | ```
|
117 | -c, --config configuration file
|
118 | -e, --exclude exclude globs from path expansion
|
119 | --fix fixes linting errors for select rules (this may overwrite linted files)
|
120 | --force return status code 0 even if there are lint errors
|
121 | -h, --help display detailed help
|
122 | -i, --init generate a tslint.json config file in the current working directory
|
123 | -o, --out output file
|
124 | --project tsconfig.json file
|
125 | -r, --rules-dir rules directory
|
126 | -s, --formatters-dir formatters directory
|
127 | -t, --format output format (prose, json, stylish, verbose, pmd, msbuild, checkstyle, vso, fileslist) [default: "prose"]
|
128 | --test test that tslint produces the correct output for the specified directory
|
129 | --type-check enable type checking when linting a project
|
130 | -v, --version current version
|
131 | ```
|
132 |
|
133 | tslint accepts the following command-line options:
|
134 |
|
135 | ```
|
136 | -c, --config:
|
137 | The location of the configuration file that tslint will use to
|
138 | determine which rules are activated and what options to provide
|
139 | to the rules. If no option is specified, the config file named
|
140 | tslint.json is used, so long as it exists in the path.
|
141 | The format of the file is { rules: { /* rules list */ } },
|
142 | where /* rules list */ is a key: value comma-separated list of
|
143 | rulename: rule-options pairs. Rule-options can be either a
|
144 | boolean true/false value denoting whether the rule is used or not,
|
145 | or a list [boolean, ...] where the boolean provides the same role
|
146 | as in the non-list case, and the rest of the list are options passed
|
147 | to the rule that will determine what it checks for (such as number
|
148 | of characters for the max-line-length rule, or what functions to ban
|
149 | for the ban rule).
|
150 |
|
151 | -e, --exclude:
|
152 | A filename or glob which indicates files to exclude from linting.
|
153 | This option can be supplied multiple times if you need multiple
|
154 | globs to indicate which files to exclude.
|
155 |
|
156 | --fix:
|
157 | Fixes linting errors for select rules. This may overwrite linted files.
|
158 |
|
159 | --force:
|
160 | Return status code 0 even if there are any lint errors.
|
161 | Useful while running TSLint via an npm script.
|
162 |
|
163 | -i, --init:
|
164 | Generates a tslint.json config file in the current working directory.
|
165 |
|
166 | -o, --out:
|
167 | A filename to output the results to. By default, tslint outputs to
|
168 | stdout, which is usually the console where you're running it from.
|
169 |
|
170 | -r, --rules-dir:
|
171 | An additional rules directory, for user-created rules.
|
172 | tslint will always check its default rules directory, in
|
173 | node_modules/tslint/lib/rules, before checking the user-provided
|
174 | rules directory, so rules in the user-provided rules directory
|
175 | with the same name as the base rules will not be loaded.
|
176 |
|
177 | -s, --formatters-dir:
|
178 | An additional formatters directory, for user-created formatters.
|
179 | Formatters are files that will format the tslint output, before
|
180 | writing it to stdout or the file passed in --out. The default
|
181 | directory, node_modules/tslint/build/formatters, will always be
|
182 | checked first, so user-created formatters with the same names
|
183 | as the base formatters will not be loaded.
|
184 |
|
185 | -t, --format:
|
186 | The formatter to use to format the results of the linter before
|
187 | outputting it to stdout or the file passed in --out. The core
|
188 | formatters are prose (human readable), json (machine readable)
|
189 | and verbose. prose is the default if this option is not used.
|
190 | Other built-in options include pmd, msbuild, checkstyle, and vso.
|
191 | Additional formatters can be added and used if the --formatters-dir
|
192 | option is set.
|
193 |
|
194 | --test:
|
195 | Runs tslint on matched directories and checks if tslint outputs
|
196 | match the expected output in .lint files. Automatically loads the
|
197 | tslint.json files in the directories as the configuration file for
|
198 | the tests. See the full tslint documentation for more details on how
|
199 | this can be used to test custom rules.
|
200 |
|
201 | --project:
|
202 | The location of a tsconfig.json file that will be used to determine which
|
203 | files will be linted.
|
204 |
|
205 | --type-check
|
206 | Enables the type checker when running linting rules. --project must be
|
207 | specified in order to enable type checking.
|
208 |
|
209 | -v, --version:
|
210 | The current version of tslint.
|
211 |
|
212 | -h, --help:
|
213 | Prints this help message.
|
214 | ```
|
215 |
|
216 | #### Library
|
217 |
|
218 | ```js
|
219 | import { Linter, Configuration } from "tslint";
|
220 | import * as fs from "fs";
|
221 |
|
222 | const fileName = "Specify input file name";
|
223 | const configurationFilename = "Specify configuration file name";
|
224 | const options = {
|
225 | formatter: "json",
|
226 | rulesDirectory: "customRules/",
|
227 | formattersDirectory: "customFormatters/"
|
228 | };
|
229 |
|
230 | const fileContents = fs.readFileSync(fileName, "utf8");
|
231 | const linter = new Linter(options);
|
232 | const configLoad = Configuration.findConfiguration(configurationFilename, filename);
|
233 | const result = linter.lint(fileName, fileContents, configLoad.results);
|
234 | ```
|
235 |
|
236 | #### Type Checking
|
237 |
|
238 | To enable rules that work with the type checker, a TypeScript program object must be passed to the linter when using the programmatic API. Helper functions are provided to create a program from a `tsconfig.json` file. A project directory can be specified if project files do not lie in the same directory as the `tsconfig.json` file.
|
239 |
|
240 | ```js
|
241 | const program = Linter.createProgram("tsconfig.json", "projectDir/");
|
242 | const files = Linter.getFileNames(program);
|
243 | const results = files.map(file => {
|
244 | const fileContents = program.getSourceFile(file).getFullText();
|
245 | const linter = new Linter(file, fileContents, options, program);
|
246 | return linter.lint();
|
247 | });
|
248 | ```
|
249 |
|
250 | When using the CLI, the `--project` flag will automatically create a program from the specified `tsconfig.json` file. Adding `--type-check` then enables rules that require the type checker.
|
251 |
|
252 |
|
253 | Core Rules
|
254 | -----
|
255 | <sup>[back to ToC ↑](#table-of-contents)</sup>
|
256 |
|
257 | _Rules_ encode logic for syntactic & semantic checks of TypeScript source code.
|
258 |
|
259 | [See the TSLint website for a list of core rules included in the `tslint` package.]
|
260 | (http://palantir.github.io/tslint/rules/)
|
261 |
|
262 | Core Formatters
|
263 | -----
|
264 | <sup>[back to ToC ↑](#table-of-contents)</sup>
|
265 |
|
266 | _Formatters_ allow for transformation of lint results into various forms before outputting to stdout or a file.
|
267 |
|
268 | [See the TSLint website for a list of core formatters included in the `tslint` package.]
|
269 | (http://palantir.github.io/tslint/formatters/)
|
270 |
|
271 | Rule Flags
|
272 | -----
|
273 | <sup>[back to ToC ↑](#table-of-contents)</sup>
|
274 |
|
275 | You may enable/disable TSLint or a subset of rules within certain lines of a file with the following comment rule flags:
|
276 |
|
277 | * `/* tslint:disable */` - Disable all rules for the rest of the file
|
278 | * `/* tslint:enable */` - Enable all rules for the rest of the file
|
279 | * `/* tslint:disable:rule1 rule2 rule3... */` - Disable the listed rules for the rest of the file
|
280 | * `/* tslint:enable:rule1 rule2 rule3... */` - Enable the listed rules for the rest of the file
|
281 | * `// tslint:disable-next-line` - Disables all rules for the following line
|
282 | * `someCode(); // tslint:disable-line` - Disables all rules for the current line
|
283 | * `// tslint:disable-next-line:rule1 rule2 rule3...` - Disables the listed rules for the next line
|
284 | * etc.
|
285 |
|
286 | Rules flags enable or disable rules as they are parsed. Disabling an already disabled rule or enabling an already enabled rule has no effect.
|
287 |
|
288 | For example, imagine the directive `/* tslint:disable */` on the first line of a file, `/* tslint:enable:ban class-name */` on the 10th line and `/* tslint:enable */` on the 20th. No rules will be checked between the 1st and 10th lines, only the `ban` and `class-name` rules will be checked between the 10th and 20th, and all rules will be checked for the remainder of the file.
|
289 |
|
290 | Custom Rules
|
291 | ------------
|
292 | <sup>[back to ToC ↑](#table-of-contents)</sup>
|
293 |
|
294 | #### Custom rule sets from Palantir
|
295 |
|
296 | - [tslint-react](https://github.com/palantir/tslint-react) - Lint rules related to React & JSX.
|
297 |
|
298 | #### Custom rule sets from the community
|
299 |
|
300 | If we don't have all the rules you're looking for, you can either write your own custom rules or use custom rules that others have developed. The repos below are a good source of custom rules:
|
301 |
|
302 | - [ESLint rules for TSLint](https://github.com/buzinas/tslint-eslint-rules) - Improve your TSLint with the missing ESLint Rules
|
303 | - [tslint-microsoft-contrib](https://github.com/Microsoft/tslint-microsoft-contrib) - A set of TSLint rules used on some Microsoft projects
|
304 | - [codelyzer](https://github.com/mgechev/codelyzer) - A set of tslint rules for static code analysis of Angular TypeScript projects
|
305 | - [vrsource-tslint-rules](https://github.com/vrsource/vrsource-tslint-rules)
|
306 |
|
307 | #### Writing custom rules
|
308 |
|
309 | TSLint ships with a set of core rules that can be configured. However, users are also allowed to write their own rules, which allows them to enforce specific behavior not covered by the core of TSLint. TSLint's internal rules are itself written to be pluggable, so adding a new rule is as simple as creating a new rule file named by convention. New rules can be written in either TypeScript or JavaScript; if written in TypeScript, the code must be compiled to JavaScript before invoking TSLint.
|
310 |
|
311 | Let us take the example of how to write a new rule to forbid all import statements (you know, *for science*). Let us name the rule file `noImportsRule.ts`. Rules are referenced in `tslint.json` with their kebab-cased identifer, so `"no-imports": true` would configure the rule.
|
312 |
|
313 | __Important conventions__:
|
314 | * Rule identifiers are always kebab-cased.
|
315 | * Rule files are always camel-cased (`camelCasedRule.ts`).
|
316 | * Rule files *must* contain the suffix `Rule`.
|
317 | * The exported class must always be named `Rule` and extend from `Lint.Rules.AbstractRule`.
|
318 |
|
319 | Now, let us first write the rule in TypeScript:
|
320 |
|
321 | ```ts
|
322 | import * as ts from "typescript";
|
323 | import { Rules, RuleFailure, RuleWalker } from "tslint";
|
324 |
|
325 | export class Rule extends Rules.AbstractRule {
|
326 | public static FAILURE_STRING = "import statement forbidden";
|
327 |
|
328 | public apply(sourceFile: ts.SourceFile): RuleFailure[] {
|
329 | return this.applyWithWalker(new NoImportsWalker(sourceFile, this.getOptions()));
|
330 | }
|
331 | }
|
332 |
|
333 | // The walker takes care of all the work.
|
334 | class NoImportsWalker extends RuleWalker {
|
335 | public visitImportDeclaration(node: ts.ImportDeclaration) {
|
336 | // create a failure at the current position
|
337 | this.addFailure(this.createFailure(node.getStart(), node.getWidth(), Rule.FAILURE_STRING));
|
338 |
|
339 | // call the base version of this visitor to actually parse this node
|
340 | super.visitImportDeclaration(node);
|
341 | }
|
342 | }
|
343 | ```
|
344 |
|
345 | Given a walker, TypeScript's parser visits the AST using the visitor pattern. So the rule walkers only need to override the appropriate visitor methods to enforce its checks. For reference, the base walker can be found in [syntaxWalker.ts](https://github.com/palantir/tslint/blob/master/src/language/walker/syntaxWalker.ts).
|
346 |
|
347 | We still need to hook up this new rule to TSLint. First make sure to compile `noImportsRule.ts`:
|
348 |
|
349 | ```bash
|
350 | tsc --noImplicitAny noImportsRule.ts
|
351 | ```
|
352 |
|
353 | Then, if using the CLI, provide the directory that contains this rule as an option to `--rules-dir`. If using TSLint as a library or via `grunt-tslint`, the `options` hash must contain `"rulesDirectory": "..."`. If you run the linter, you'll see that we have now successfully banned all import statements via TSLint!
|
354 |
|
355 | Finally, enable each custom rule in your [`tslint.json` config file](https://palantir.github.io/tslint/usage/tslint-json/) config file.
|
356 |
|
357 | Final notes:
|
358 |
|
359 | - Core rules cannot be overwritten with a custom implementation.
|
360 | - Custom rules can also take in options just like core rules (retrieved via `this.getOptions()`).
|
361 |
|
362 | Custom Formatters
|
363 | -----------------
|
364 | <sup>[back to ToC ↑](#table-of-contents)</sup>
|
365 |
|
366 | Just like rules, additional formatters can also be supplied to TSLint via `--formatters-dir` on the CLI or `formattersDirectory` option on the library or `grunt-tslint`. Writing a new formatter is simpler than writing a new rule, as shown in the JSON formatter's code.
|
367 |
|
368 | ```typescript
|
369 | import * as ts from "typescript";
|
370 | import { Formatters, RuleFailure } from "tslint";
|
371 |
|
372 | export class Formatter extends Formatters.AbstractFormatter {
|
373 | public format(failures: RuleFailure[]): string {
|
374 | var failuresJSON = failures.map((failure: RuleFailure) => failure.toJson());
|
375 | return JSON.stringify(failuresJSON);
|
376 | }
|
377 | }
|
378 | ```
|
379 |
|
380 | Such custom formatters can also be written in JavaScript. Formatter files are always named with the suffix `Formatter` and the exported class within the file must be named `Formatter`. A formatter is referenced from TSLint without its suffix.
|
381 |
|
382 | Development
|
383 | -----------
|
384 | <sup>[back to ToC ↑](#table-of-contents)</sup>
|
385 |
|
386 | Requirements:
|
387 |
|
388 | - `node` v7
|
389 | - `yarn` v0.18
|
390 |
|
391 | #### Quick Start
|
392 |
|
393 | ```bash
|
394 | git clone git@github.com:palantir/tslint.git --config core.autocrlf=input --config core.eol=lf
|
395 | yarn install
|
396 | yarn compile
|
397 | yarn test
|
398 | ```
|
399 |
|
400 | #### `next` branch
|
401 |
|
402 | The [`next` branch of this repo](https://github.com/palantir/tslint/tree/next) tracks the latest TypeScript compiler
|
403 | nightly release as a `peerDependency`. This allows you to develop the linter and its rules against the latest features of the
|
404 | language. Releases from this branch are published to NPM with the `next` dist-tag, so you may install the latest dev
|
405 | version of TSLint via `npm install tslint@next`.
|
406 |
|
407 | Creating a new release
|
408 | ----------------------
|
409 | <sup>[back to ToC ↑](#table-of-contents)</sup>
|
410 |
|
411 | 1. Bump the version number in `package.json` and `src/tslintMulti.ts`
|
412 | 2. Add release notes in `CHANGELOG.md`
|
413 | 3. `yarn verify` to build the latest sources
|
414 | 4. Commit with message `Prepare release <version>`
|
415 | 5. Run `npm publish`
|
416 | 6. Create a git tag for the new release and push it ([see existing tags here](https://github.com/palantir/tslint/tags))
|