From 3292002f19d1d631d2d8767baf38d541b758c758 Mon Sep 17 00:00:00 2001 From: Brad Zacher Date: Fri, 20 May 2022 08:33:53 -0700 Subject: [PATCH] feat: [4.7] support new extensions --- docs/linting/README.md | 8 +-- docs/linting/TROUBLESHOOTING.md | 4 +- packages/eslint-plugin/README.md | 2 +- .../rules/explicit-function-return-type.md | 4 +- .../rules/explicit-member-accessibility.md | 4 +- .../rules/explicit-module-boundary-types.md | 4 +- .../src/configs/eslint-recommended.ts | 2 +- packages/eslint-plugin/src/util/misc.ts | 13 ++++- packages/parser/README.md | 24 +++++---- packages/parser/src/parser.ts | 9 +--- packages/typescript-estree/README.md | 2 +- .../create-program/createIsolatedProgram.ts | 9 ++-- .../create-program/createProjectProgram.ts | 12 ++++- .../src/create-program/createSourceFile.ts | 4 +- .../src/create-program/getScriptKind.ts | 49 +++++++++++++++++++ .../src/create-program/shared.ts | 44 +++++------------ packages/typescript-estree/src/index.ts | 1 + packages/typescript-estree/src/parser.ts | 6 ++- 18 files changed, 125 insertions(+), 76 deletions(-) create mode 100644 packages/typescript-estree/src/create-program/getScriptKind.ts diff --git a/docs/linting/README.md b/docs/linting/README.md index e42c436bd1d1..bf2a0f5ffe8f 100644 --- a/docs/linting/README.md +++ b/docs/linting/README.md @@ -85,27 +85,27 @@ With that configured, open a terminal to the root of your project, and run the f ```bash -npx eslint . --ext .js,.jsx,.ts,.tsx +npx eslint . --ext .js,.mjs,.cjs,.jsx,.ts,.mts,.cts,.tsx ``` ```bash -yarn eslint . --ext .js,.jsx,.ts,.tsx +yarn eslint . --ext .js,.mjs,.cjs,.jsx,.ts,.mts,.cts,.tsx ``` -That's it - ESLint will lint all `.js`, `.jsx`, `.ts`, and `.tsx` files within the current folder, and will output the results to your terminal. +That's it - ESLint will lint all TypeScript compatible files within the current folder, and will output the results to your terminal. You are also recommended to add an npm script in your package.json, so you don't have to repeat the same command every time you run ESLint. ```json title="package.json" { "scripts": { - "lint": "eslint . --ext .js,.jsx,.ts,.tsx" + "lint": "eslint . --ext .js,.mjs,.cjs,.jsx,.ts,.mts,.cts,.tsx" } } ``` diff --git a/docs/linting/TROUBLESHOOTING.md b/docs/linting/TROUBLESHOOTING.md index 8f8ae10565de..7998259526ac 100644 --- a/docs/linting/TROUBLESHOOTING.md +++ b/docs/linting/TROUBLESHOOTING.md @@ -119,12 +119,12 @@ As of our v4.0.0 release, this also applies to types. If you use global types from a 3rd party package (i.e. anything from an `@types` package), then you will have to configure ESLint appropriately to define these global types. For example; the `JSX` namespace from `@types/react` is a global 3rd party type that you must define in your ESLint config. -Note, that for a mixed project including JavaScript and TypeScript, the `no-undef` rule (like any role) can be turned off for TypeScript files alone by adding an `overrides` section to .eslintrc.json: +Note, that for a mixed project including JavaScript and TypeScript, the `no-undef` rule (like any role) can be turned off for TypeScript files alone by adding an `overrides` section to `.eslintrc.cjs`: ```json "overrides": [ { - "files": ["*.ts"], + "files": ["*.ts", "*.mts", "*.cts", "*.tsx"], "rules": { "no-undef": "off" } diff --git a/packages/eslint-plugin/README.md b/packages/eslint-plugin/README.md index 999924414dde..a67c6ece662f 100644 --- a/packages/eslint-plugin/README.md +++ b/packages/eslint-plugin/README.md @@ -59,7 +59,7 @@ You can also enable all the recommended rules for our plugin. Add `plugin:@types } ``` -**Note: Make sure to use `eslint --ext .js,.ts` since by [default](https://eslint.org/docs/user-guide/command-line-interface#--ext) `eslint` will only search for `.js` files.** +**Note: Make sure to use `eslint --ext .js,.mjs,.cjs,.jsx,.ts,.mts,.cts,.tsx` since by [default](https://eslint.org/docs/user-guide/command-line-interface#--ext) `eslint` will only search for `.js` files.** ### Recommended Configs diff --git a/packages/eslint-plugin/docs/rules/explicit-function-return-type.md b/packages/eslint-plugin/docs/rules/explicit-function-return-type.md index 210871ab3478..8faf8aab503a 100644 --- a/packages/eslint-plugin/docs/rules/explicit-function-return-type.md +++ b/packages/eslint-plugin/docs/rules/explicit-function-return-type.md @@ -95,7 +95,7 @@ const defaults = { ### Configuring in a mixed JS/TS codebase -If you are working on a codebase within which you lint non-TypeScript code (i.e. `.js`/`.jsx`), you should ensure that you should use [ESLint `overrides`](https://eslint.org/docs/user-guide/configuring#disabling-rules-only-for-a-group-of-files) to only enable the rule on `.ts`/`.tsx` files. If you don't, then you will get unfixable lint errors reported within `.js`/`.jsx` files. +If you are working on a codebase within which you lint non-TypeScript code (i.e. `.js`/`.mjs`/`.cjs`/`.jsx`), you should ensure that you should use [ESLint `overrides`](https://eslint.org/docs/user-guide/configuring#disabling-rules-only-for-a-group-of-files) to only enable the rule on `.ts`/`.mts`/`.cts`/`.tsx` files. If you don't, then you will get unfixable lint errors reported within `.js`/`.mjs`/`.cjs`/`.jsx` files. ```jsonc { @@ -106,7 +106,7 @@ If you are working on a codebase within which you lint non-TypeScript code (i.e. "overrides": [ { // enable the rule specifically for TypeScript files - "files": ["*.ts", "*.tsx"], + "files": ["*.ts", "*.mts", "*.cts", "*.tsx"], "rules": { "@typescript-eslint/explicit-function-return-type": ["error"] } diff --git a/packages/eslint-plugin/docs/rules/explicit-member-accessibility.md b/packages/eslint-plugin/docs/rules/explicit-member-accessibility.md index 4d14797d02c1..7570e6e4667a 100644 --- a/packages/eslint-plugin/docs/rules/explicit-member-accessibility.md +++ b/packages/eslint-plugin/docs/rules/explicit-member-accessibility.md @@ -39,7 +39,7 @@ const defaultOptions: Options = { ### Configuring in a mixed JS/TS codebase -If you are working on a codebase within which you lint non-TypeScript code (i.e. `.js`/`.jsx`), you should ensure that you should use [ESLint `overrides`](https://eslint.org/docs/user-guide/configuring#disabling-rules-only-for-a-group-of-files) to only enable the rule on `.ts`/`.tsx` files. If you don't, then you will get unfixable lint errors reported within `.js`/`.jsx` files. +If you are working on a codebase within which you lint non-TypeScript code (i.e. `.js`/`.mjs`/`.cjs`/`.jsx`), you should ensure that you should use [ESLint `overrides`](https://eslint.org/docs/user-guide/configuring#disabling-rules-only-for-a-group-of-files) to only enable the rule on `.ts`/`.mts`/`.cts`/`.tsx` files. If you don't, then you will get unfixable lint errors reported within `.js`/`.mjs`/`.cjs`/`.jsx` files. ```jsonc { @@ -50,7 +50,7 @@ If you are working on a codebase within which you lint non-TypeScript code (i.e. "overrides": [ { // enable the rule specifically for TypeScript files - "files": ["*.ts", "*.tsx"], + "files": ["*.ts", "*.mts", "*.cts", "*.tsx"], "rules": { "@typescript-eslint/explicit-member-accessibility": ["error"] } diff --git a/packages/eslint-plugin/docs/rules/explicit-module-boundary-types.md b/packages/eslint-plugin/docs/rules/explicit-module-boundary-types.md index d968504be074..26809892e678 100644 --- a/packages/eslint-plugin/docs/rules/explicit-module-boundary-types.md +++ b/packages/eslint-plugin/docs/rules/explicit-module-boundary-types.md @@ -110,7 +110,7 @@ const defaults = { ### Configuring in a mixed JS/TS codebase -If you are working on a codebase within which you lint non-TypeScript code (i.e. `.js`/`.jsx`), you should ensure that you should use [ESLint `overrides`](https://eslint.org/docs/user-guide/configuring#disabling-rules-only-for-a-group-of-files) to only enable the rule on `.ts`/`.tsx` files. If you don't, then you will get unfixable lint errors reported within `.js`/`.jsx` files. +If you are working on a codebase within which you lint non-TypeScript code (i.e. `.js`/`.mjs`/`.cjs`/`.jsx`), you should ensure that you should use [ESLint `overrides`](https://eslint.org/docs/user-guide/configuring#disabling-rules-only-for-a-group-of-files) to only enable the rule on `.ts`/`.mts`/`.cts`/`.tsx` files. If you don't, then you will get unfixable lint errors reported within `.js`/`.mjs`/`.cjs`/`.jsx` files. ```jsonc { @@ -121,7 +121,7 @@ If you are working on a codebase within which you lint non-TypeScript code (i.e. "overrides": [ { // enable the rule specifically for TypeScript files - "files": ["*.ts", "*.tsx"], + "files": ["*.ts", "*.mts", "*.cts", "*.tsx"], "rules": { "@typescript-eslint/explicit-module-boundary-types": ["error"] } diff --git a/packages/eslint-plugin/src/configs/eslint-recommended.ts b/packages/eslint-plugin/src/configs/eslint-recommended.ts index 125c093b2bc2..71443e1f52ef 100644 --- a/packages/eslint-plugin/src/configs/eslint-recommended.ts +++ b/packages/eslint-plugin/src/configs/eslint-recommended.ts @@ -6,7 +6,7 @@ export = { overrides: [ { - files: ['*.ts', '*.tsx'], + files: ['*.ts', '*.tsx', '*.mts', '*.cts'], rules: { 'constructor-super': 'off', // ts(2335) & ts(2377) 'getter-return': 'off', // ts(2378) diff --git a/packages/eslint-plugin/src/util/misc.ts b/packages/eslint-plugin/src/util/misc.ts index 8479feb728dd..59a7ccd9fc46 100644 --- a/packages/eslint-plugin/src/util/misc.ts +++ b/packages/eslint-plugin/src/util/misc.ts @@ -4,12 +4,23 @@ import { AST_NODE_TYPES, TSESLint, TSESTree } from '@typescript-eslint/utils'; import { requiresQuoting } from '@typescript-eslint/type-utils'; +import * as ts from 'typescript'; +const DEFINITION_EXTENSIONS = [ + ts.Extension.Dts, + ts.Extension.Dcts, + ts.Extension.Dmts, +] as const; /** * Check if the context file name is *.d.ts or *.d.tsx */ function isDefinitionFile(fileName: string): boolean { - return /\.d\.tsx?$/i.test(fileName || ''); + for (const definitionExt of DEFINITION_EXTENSIONS) { + if (fileName.endsWith(definitionExt)) { + return true; + } + } + return false; } /** diff --git a/packages/parser/README.md b/packages/parser/README.md index 81df05194977..f026a5b4ae2e 100644 --- a/packages/parser/README.md +++ b/packages/parser/README.md @@ -78,16 +78,19 @@ Default `false`. Enable parsing JSX when `true`. More details can be found [here](https://www.typescriptlang.org/docs/handbook/jsx.html). -**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: +**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. -- if `parserOptions.project` is _not_ provided: - - `.js`, `.jsx`, `.tsx` files are parsed as if this is true. - - `.ts` files are parsed as if this is false. - - unknown extensions (`.md`, `.vue`) will respect this setting. -- if `parserOptions.project` is provided (i.e. you are using rules with type information): - - `.js`, `.jsx`, `.tsx` files are parsed as if this is true. - - `.ts` files are parsed as if this is false. - - "unknown" extensions (`.md`, `.vue`) **are parsed as if this is false**. + + +The exact behavior is as follows: + +- `.js`, `.mjs`, `.cjs`, `.jsx`, `.tsx` files are always parsed as if this is `true`. +- `.ts`, `.mts`, `.cts` files are always parsed as if this is `false`. +- For "unknown" extensions (`.md`, `.vue`): + - If `parserOptions.project` is _not_ provided: + - The setting will be respected. + - If `parserOptions.project` is provided (i.e. you are using rules with type information): + - **always parsed as if this is `false`,** ### `parserOptions.ecmaFeatures.globalReturn` @@ -203,7 +206,8 @@ For example, by default it will ensure that a glob like `./**/tsconfig.json` wil Default `undefined`. This option allows you to provide one or more additional file extensions which should be considered in the TypeScript Program compilation. -The 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"]`. +The default extensions are `['.js', '.mjs', '.cjs', '.jsx', '.ts', '.mts', '.cts', '.tsx']`. +Add extensions starting with `.`, followed by the file extension. E.g. for a `.vue` file use `"extraFileExtensions": [".vue"]`. ### `parserOptions.warnOnUnsupportedTypeScriptVersion` diff --git a/packages/parser/src/parser.ts b/packages/parser/src/parser.ts index 365bff6648f8..7fcd45f96f75 100644 --- a/packages/parser/src/parser.ts +++ b/packages/parser/src/parser.ts @@ -36,7 +36,7 @@ function validateBoolean( return value; } -const LIB_FILENAME_REGEX = /lib\.(.+)\.d\.ts$/; +const LIB_FILENAME_REGEX = /lib\.(.+)\.d\.[cm]?ts$/; function getLib(compilerOptions: CompilerOptions): Lib[] { if (compilerOptions.lib) { return compilerOptions.lib.reduce((acc, lib) => { @@ -110,13 +110,6 @@ function parseForESLint( sourceType: options.sourceType, }; - if (typeof options.filePath === 'string') { - const tsx = options.filePath.endsWith('.tsx'); - if (tsx || options.filePath.endsWith('.ts')) { - parserOptions.jsx = tsx; - } - } - /** * Allow the user to suppress the warning from typescript-estree if they are using an unsupported * version of TypeScript diff --git a/packages/typescript-estree/README.md b/packages/typescript-estree/README.md index f235f3dcf212..02946daa80df 100644 --- a/packages/typescript-estree/README.md +++ b/packages/typescript-estree/README.md @@ -69,7 +69,7 @@ interface ParseOptions { * Enable parsing of JSX. * For more details, see https://www.typescriptlang.org/docs/handbook/jsx.html * - * NOTE: this setting does not effect known file types (.js, .jsx, .ts, .tsx, .json) because the + * 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 diff --git a/packages/typescript-estree/src/create-program/createIsolatedProgram.ts b/packages/typescript-estree/src/create-program/createIsolatedProgram.ts index 70169c66891b..c4392941bb67 100644 --- a/packages/typescript-estree/src/create-program/createIsolatedProgram.ts +++ b/packages/typescript-estree/src/create-program/createIsolatedProgram.ts @@ -1,11 +1,8 @@ import debug from 'debug'; import * as ts from 'typescript'; import { Extra } from '../parser-options'; -import { - ASTAndProgram, - createDefaultCompilerOptionsFromExtra, - getScriptKind, -} from './shared'; +import { ASTAndProgram, createDefaultCompilerOptionsFromExtra } from './shared'; +import { getScriptKind } from './getScriptKind'; const log = debug('typescript-eslint:typescript-estree:createIsolatedProgram'); @@ -47,7 +44,7 @@ function createIsolatedProgram(code: string, extra: Extra): ASTAndProgram { code, ts.ScriptTarget.Latest, /* setParentNodes */ true, - getScriptKind(extra, filename), + getScriptKind(extra.filePath, extra.jsx), ); }, readFile() { diff --git a/packages/typescript-estree/src/create-program/createProjectProgram.ts b/packages/typescript-estree/src/create-program/createProjectProgram.ts index 69903a5bcafc..4558cc36b55b 100644 --- a/packages/typescript-estree/src/create-program/createProjectProgram.ts +++ b/packages/typescript-estree/src/create-program/createProjectProgram.ts @@ -1,5 +1,6 @@ import debug from 'debug'; import path from 'path'; +import * as ts from 'typescript'; import { getProgramsForProjects } from './createWatchProgram'; import { firstDefined } from '../node-utils'; import { Extra } from '../parser-options'; @@ -7,7 +8,16 @@ import { ASTAndProgram, getAstFromProgram } from './shared'; const log = debug('typescript-eslint:typescript-estree:createProjectProgram'); -const DEFAULT_EXTRA_FILE_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx']; +const DEFAULT_EXTRA_FILE_EXTENSIONS = [ + ts.Extension.Ts, + ts.Extension.Tsx, + ts.Extension.Js, + ts.Extension.Jsx, + ts.Extension.Mjs, + ts.Extension.Mts, + ts.Extension.Cjs, + ts.Extension.Cts, +] as readonly string[]; /** * @param code The code of the file being linted diff --git a/packages/typescript-estree/src/create-program/createSourceFile.ts b/packages/typescript-estree/src/create-program/createSourceFile.ts index 70820c1d2172..e3c6acf6dffb 100644 --- a/packages/typescript-estree/src/create-program/createSourceFile.ts +++ b/packages/typescript-estree/src/create-program/createSourceFile.ts @@ -1,7 +1,7 @@ import debug from 'debug'; import * as ts from 'typescript'; import { Extra } from '../parser-options'; -import { getScriptKind } from './shared'; +import { getScriptKind } from './getScriptKind'; const log = debug('typescript-eslint:typescript-estree:createSourceFile'); @@ -17,7 +17,7 @@ function createSourceFile(code: string, extra: Extra): ts.SourceFile { code, ts.ScriptTarget.Latest, /* setParentNodes */ true, - getScriptKind(extra), + getScriptKind(extra.filePath, extra.jsx), ); } diff --git a/packages/typescript-estree/src/create-program/getScriptKind.ts b/packages/typescript-estree/src/create-program/getScriptKind.ts new file mode 100644 index 000000000000..35b77c3b3dea --- /dev/null +++ b/packages/typescript-estree/src/create-program/getScriptKind.ts @@ -0,0 +1,49 @@ +import path from 'path'; +import * as ts from 'typescript'; + +function getScriptKind(filePath: string, jsx: boolean): ts.ScriptKind { + const extension = path.extname(filePath).toLowerCase(); + // note - we respect the user's extension when it is known we could override it and force it to match their + // jsx setting, but that could create weird situations where we throw parse errors when TSC doesn't + // https://github.com/microsoft/TypeScript/blob/da00ba67ed1182ad334f7c713b8254fba174aeba/src/compiler/utilities.ts#L6948-L6968 + switch (extension) { + case ts.Extension.Js: + case ts.Extension.Cjs: + case ts.Extension.Mjs: + return ts.ScriptKind.JS; + + case ts.Extension.Jsx: + return ts.ScriptKind.JSX; + + case ts.Extension.Ts: + case ts.Extension.Cts: + case ts.Extension.Mts: + return ts.ScriptKind.TS; + + case ts.Extension.Tsx: + return ts.ScriptKind.TSX; + + case ts.Extension.Json: + return ts.ScriptKind.JSON; + + default: + // unknown extension, force typescript to ignore the file extension, and respect the user's setting + return jsx ? ts.ScriptKind.TSX : ts.ScriptKind.TS; + } +} + +function getLanguageVariant(scriptKind: ts.ScriptKind): ts.LanguageVariant { + // https://github.com/microsoft/TypeScript/blob/d6e483b8dabd8fd37c00954c3f2184bb7f1eb90c/src/compiler/utilities.ts#L6281-L6285 + switch (scriptKind) { + case ts.ScriptKind.TSX: + case ts.ScriptKind.JSX: + case ts.ScriptKind.JS: + case ts.ScriptKind.JSON: + return ts.LanguageVariant.JSX; + + default: + return ts.LanguageVariant.Standard; + } +} + +export { getScriptKind, getLanguageVariant }; diff --git a/packages/typescript-estree/src/create-program/shared.ts b/packages/typescript-estree/src/create-program/shared.ts index 53d6fe9ee4de..e202e7ff40bc 100644 --- a/packages/typescript-estree/src/create-program/shared.ts +++ b/packages/typescript-estree/src/create-program/shared.ts @@ -72,40 +72,23 @@ function canonicalDirname(p: CanonicalPath): CanonicalPath { return path.dirname(p) as CanonicalPath; } -function getScriptKind( - extra: Extra, - filePath: string = extra.filePath, -): ts.ScriptKind { - const extension = path.extname(filePath).toLowerCase(); - // note - we respect the user's extension when it is known we could override it and force it to match their - // jsx setting, but that could create weird situations where we throw parse errors when TSC doesn't - switch (extension) { - case '.ts': - return ts.ScriptKind.TS; - - case '.tsx': - return ts.ScriptKind.TSX; - - case '.js': - return ts.ScriptKind.JS; - - case '.jsx': - return ts.ScriptKind.JSX; - - case '.json': - return ts.ScriptKind.JSON; - - default: - // unknown extension, force typescript to ignore the file extension, and respect the user's setting - return extra.jsx ? ts.ScriptKind.TSX : ts.ScriptKind.TS; - } -} - +const DEFINITION_EXTENSIONS = [ + ts.Extension.Dts, + ts.Extension.Dcts, + ts.Extension.Dmts, +] as const; function getExtension(fileName: string | undefined): string | null { if (!fileName) { return null; } - return fileName.endsWith('.d.ts') ? '.d.ts' : path.extname(fileName); + + for (const definitionExt of DEFINITION_EXTENSIONS) { + if (fileName.endsWith(definitionExt)) { + return definitionExt; + } + } + + return path.extname(fileName); } function getAstFromProgram( @@ -149,7 +132,6 @@ export { createDefaultCompilerOptionsFromExtra, ensureAbsolutePath, getCanonicalFileName, - getScriptKind, getAstFromProgram, getModuleResolver, }; diff --git a/packages/typescript-estree/src/index.ts b/packages/typescript-estree/src/index.ts index a922ef199cf7..fda8b30032f5 100644 --- a/packages/typescript-estree/src/index.ts +++ b/packages/typescript-estree/src/index.ts @@ -12,6 +12,7 @@ export { simpleTraverse } from './simple-traverse'; export * from './ts-estree'; export { clearWatchCaches as clearCaches } from './create-program/createWatchProgram'; export { createProgramFromConfigFile as createProgram } from './create-program/useProvidedPrograms'; +export * from './create-program/getScriptKind'; // re-export for backwards-compat export { visitorKeys } from '@typescript-eslint/visitor-keys'; diff --git a/packages/typescript-estree/src/parser.ts b/packages/typescript-estree/src/parser.ts index a0c952b4db52..cce73b952487 100644 --- a/packages/typescript-estree/src/parser.ts +++ b/packages/typescript-estree/src/parser.ts @@ -237,8 +237,10 @@ function applyParserOptionsToExtra(options: TSESTreeOptions): void { /** * Enable JSX - note the applicable file extension is still required */ - if (typeof options.jsx === 'boolean' && options.jsx) { - extra.jsx = true; + if (typeof options.jsx !== 'boolean') { + extra.jsx = false; + } else { + extra.jsx = options.jsx; } /**