-
Notifications
You must be signed in to change notification settings - Fork 362
/
eslint.ts
448 lines (378 loc) · 12.6 KB
/
eslint.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
import { Project } from "..";
import { PROJEN_RC } from "../common";
import { Component } from "../component";
import { NodeProject } from "../javascript";
import { JsonFile } from "../json";
import { Prettier } from "./prettier";
export interface EslintOptions {
/**
* Path to `tsconfig.json` which should be used by eslint.
* @default "./tsconfig.json"
*/
readonly tsconfigPath?: string;
/**
* Directories with source files to lint (e.g. [ "src" ])
*/
readonly dirs: string[];
/**
* Directories with source files that include tests and build tools. These
* sources are linted but may also import packages from `devDependencies`.
* @default []
*/
readonly devdirs?: string[];
/**
* File types that should be linted (e.g. [ ".js", ".ts" ])
* @default [".ts"]
*/
readonly fileExtensions?: string[];
/**
* List of file patterns that should not be linted, using the same syntax
* as .gitignore patterns.
*
* @default [ '*.js', '*.d.ts', 'node_modules/', '*.generated.ts', 'coverage' ]
*/
readonly ignorePatterns?: string[];
/**
* Projenrc file to lint. Use empty string to disable.
* @default PROJEN_RC
*/
readonly lintProjenRcFile?: string;
/**
* Should we lint .projenrc.js
* @default true
* @deprecated use lintProjenRcFile instead
*/
readonly lintProjenRc?: boolean;
/**
* Enable prettier for code formatting
* @default false
*/
readonly prettier?: boolean;
/**
* Enable import alias for module paths
* @default undefined
*/
readonly aliasMap?: { [key: string]: string };
/**
* Enable import alias for module paths
* @default undefined
*/
readonly aliasExtensions?: string[];
/**
* Always try to resolve types under `<root>@types` directory even it doesn't contain any source code.
* This prevents `import/no-unresolved` eslint errors when importing a `@types/*` module that would otherwise remain unresolved.
* @default true
*/
readonly tsAlwaysTryTypes?: boolean;
}
/**
* eslint rules override
*/
export interface EslintOverride {
/**
* Files or file patterns on which to apply the override
*/
readonly files: string[];
/**
* The overriden rules
*/
readonly rules: { [rule: string]: any };
}
/**
* Represents eslint configuration.
*/
export class Eslint extends Component {
/**
* Returns the singletone Eslint component of a project or undefined if there is none.
*/
public static of(project: Project): Eslint | undefined {
const isEslint = (c: Component): c is Eslint => c instanceof Eslint;
return project.components.find(isEslint);
}
/**
* eslint rules.
*/
public readonly rules: { [rule: string]: any[] };
/**
* eslint overrides.
*/
public readonly overrides: EslintOverride[];
/**
* Direct access to the eslint configuration (escape hatch)
*/
public readonly config: any;
/**
* File patterns that should not be linted
*/
public readonly ignorePatterns: string[];
private _formattingRules: Record<string, any>;
private readonly _allowDevDeps: Set<string>;
private readonly _plugins = new Array<string>();
private readonly _extends = new Array<string>();
private readonly nodeProject: NodeProject;
constructor(project: NodeProject, options: EslintOptions) {
super(project);
this.nodeProject = project;
project.addDevDeps(
"eslint@^8",
"@typescript-eslint/eslint-plugin@^5",
"@typescript-eslint/parser@^5",
"eslint-import-resolver-node",
"eslint-import-resolver-typescript",
"eslint-plugin-import",
"json-schema"
);
if (options.aliasMap) {
project.addDevDeps("eslint-import-resolver-alias");
}
const devdirs = options.devdirs ?? [];
const dirs = [...options.dirs, ...devdirs];
const fileExtensions = options.fileExtensions ?? [".ts"];
this._allowDevDeps = new Set((devdirs ?? []).map((dir) => `**/${dir}/**`));
const lintProjenRc = options.lintProjenRc ?? true;
const lintProjenRcFile = options.lintProjenRcFile ?? PROJEN_RC;
const eslint = project.addTask("eslint", {
description: "Runs eslint against the codebase",
exec: [
"eslint",
`--ext ${fileExtensions.join(",")}`,
"--fix",
"--no-error-on-unmatched-pattern",
...dirs,
...(lintProjenRc && lintProjenRcFile ? [lintProjenRcFile] : []),
].join(" "),
});
project.testTask.spawn(eslint);
// exclude some files
project.npmignore?.exclude("/.eslintrc.json");
this._formattingRules = {
// see https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/indent.md
indent: ["off"],
"@typescript-eslint/indent": ["error", 2],
// Style
quotes: ["error", "single", { avoidEscape: true }],
"comma-dangle": ["error", "always-multiline"], // ensures clean diffs, see https://medium.com/@nikgraf/why-you-should-enforce-dangling-commas-for-multiline-statements-d034c98e36f8
"comma-spacing": ["error", { before: false, after: true }], // space after, no space before
"no-multi-spaces": ["error", { ignoreEOLComments: false }], // no multi spaces
"array-bracket-spacing": ["error", "never"], // [1, 2, 3]
"array-bracket-newline": ["error", "consistent"], // enforce consistent line breaks between brackets
"object-curly-spacing": ["error", "always"], // { key: 'value' }
"object-curly-newline": ["error", { multiline: true, consistent: true }], // enforce consistent line breaks between braces
"object-property-newline": [
"error",
{ allowAllPropertiesOnSameLine: true },
], // enforce "same line" or "multiple line" on object properties
"keyword-spacing": ["error"], // require a space before & after keywords
"brace-style": ["error", "1tbs", { allowSingleLine: true }], // enforce one true brace style
"space-before-blocks": ["error"], // require space before blocks
curly: ["error", "multi-line", "consistent"], // require curly braces for multiline control statements
"@typescript-eslint/member-delimiter-style": ["error"],
// Require semicolons
semi: ["error", "always"],
// Max line lengths
"max-len": [
"error",
{
code: 150,
ignoreUrls: true, // Most common reason to disable it
ignoreStrings: true, // These are not fantastic but necessary for error messages
ignoreTemplateLiterals: true,
ignoreComments: true,
ignoreRegExpLiterals: true,
},
],
// Don't unnecessarily quote properties
"quote-props": ["error", "consistent-as-needed"],
};
this.rules = {
// Require use of the `import { foo } from 'bar';` form instead of `import foo = require('bar');`
"@typescript-eslint/no-require-imports": ["error"],
// Require all imported dependencies are actually declared in package.json
"import/no-extraneous-dependencies": [
"error",
{
// Only allow importing devDependencies from "devdirs".
devDependencies: () => this.renderDevDepsAllowList(),
optionalDependencies: false, // Disallow importing optional dependencies (those shouldn't be in use in the project)
peerDependencies: true, // Allow importing peer dependencies (that aren't also direct dependencies)
},
],
// Require all imported libraries actually resolve (!!required for import/no-extraneous-dependencies to work!!)
"import/no-unresolved": ["error"],
// Require an ordering on all imports
"import/order": [
"warn",
{
groups: ["builtin", "external"],
alphabetize: { order: "asc", caseInsensitive: true },
},
],
// Cannot import from the same module twice
"no-duplicate-imports": ["error"],
// Cannot shadow names
"no-shadow": ["off"],
"@typescript-eslint/no-shadow": ["error"],
// Required spacing in property declarations (copied from TSLint, defaults are good)
"key-spacing": ["error"],
// No multiple empty lines
"no-multiple-empty-lines": ["error"],
// One of the easiest mistakes to make
"@typescript-eslint/no-floating-promises": ["error"],
// Make sure that inside try/catch blocks, promises are 'return await'ed
// (must disable the base rule as it can report incorrect errors)
"no-return-await": ["off"],
"@typescript-eslint/return-await": ["error"],
// Useless diff results
"no-trailing-spaces": ["error"],
// Must use foo.bar instead of foo['bar'] if possible
"dot-notation": ["error"],
// Are you sure | is not a typo for || ?
"no-bitwise": ["error"],
// Member ordering
"@typescript-eslint/member-ordering": [
"error",
{
default: [
"public-static-field",
"public-static-method",
"protected-static-field",
"protected-static-method",
"private-static-field",
"private-static-method",
"field",
// Constructors
"constructor", // = ["public-constructor", "protected-constructor", "private-constructor"]
// Methods
"method",
],
},
],
};
// Overrides for .projenrc.js
this.overrides = [
{
files: [lintProjenRcFile || PROJEN_RC],
rules: {
"@typescript-eslint/no-require-imports": "off",
"import/no-extraneous-dependencies": "off",
},
},
];
this.ignorePatterns = options.ignorePatterns ?? [
"*.js",
`!${lintProjenRcFile || PROJEN_RC}`,
"*.d.ts",
"node_modules/",
"*.generated.ts",
"coverage",
];
const tsconfig = options.tsconfigPath ?? "./tsconfig.json";
this.addPlugins("@typescript-eslint");
this.addPlugins("import");
this.addExtends("plugin:import/typescript");
this.config = {
env: {
jest: true,
node: true,
},
root: true,
plugins: () => this._plugins,
parser: "@typescript-eslint/parser",
parserOptions: {
ecmaVersion: 2018,
sourceType: "module",
project: tsconfig,
},
extends: () => this._extends,
settings: {
"import/parsers": {
"@typescript-eslint/parser": [".ts", ".tsx"],
},
"import/resolver": {
...(options.aliasMap && {
alias: {
map: Object.entries(options.aliasMap).map(([k, v]) => [k, v]),
extensions: options.aliasExtensions,
},
}),
node: {},
typescript: {
project: tsconfig,
...(options.tsAlwaysTryTypes !== false && { alwaysTryTypes: true }),
},
},
},
ignorePatterns: this.ignorePatterns,
rules: () => ({ ...this._formattingRules, ...this.rules }),
overrides: this.overrides,
};
new JsonFile(project, ".eslintrc.json", {
obj: this.config,
marker: false,
});
// if the user enabled prettier explicitly _or_ if the project has a
// `Prettier` component, we shall tweak our configuration accordingly.
if (options.prettier || Prettier.of(project)) {
this.enablePrettier();
}
}
/**
* Add an eslint rule.
*/
public addRules(rules: { [rule: string]: any }) {
for (const [k, v] of Object.entries(rules)) {
this.rules[k] = v;
}
}
/**
* Adds an eslint plugin
* @param plugins The names of plugins to add
*/
public addPlugins(...plugins: string[]) {
this._plugins.push(...plugins);
}
/**
* Add an eslint override.
*/
public addOverride(override: EslintOverride) {
this.overrides.push(override);
}
/**
* Do not lint these files.
*/
public addIgnorePattern(pattern: string) {
this.ignorePatterns.push(pattern);
}
/**
* Adds an `extends` item to the eslint configuration.
* @param extendList The list of "extends" to add.
*/
public addExtends(...extendList: string[]) {
this._extends.push(...extendList);
}
/**
* Add a glob file pattern which allows importing dev dependencies.
* @param pattern glob pattern.
*/
public allowDevDeps(pattern: string) {
this._allowDevDeps.add(pattern);
}
/**
* Enables prettier for code formatting.
*/
private enablePrettier() {
this.nodeProject.addDevDeps(
"prettier",
"eslint-plugin-prettier",
"eslint-config-prettier"
);
this.addPlugins("prettier");
this._formattingRules = {
"prettier/prettier": ["error"],
};
this.addExtends("prettier", "plugin:prettier/recommended");
}
private renderDevDepsAllowList() {
return Array.from(this._allowDevDeps);
}
}