Skip to content

Commit

Permalink
feat: [4.7] support new extensions
Browse files Browse the repository at this point in the history
  • Loading branch information
bradzacher committed May 20, 2022
1 parent 7e7b24c commit 3292002
Show file tree
Hide file tree
Showing 18 changed files with 125 additions and 76 deletions.
8 changes: 4 additions & 4 deletions docs/linting/README.md
Expand Up @@ -85,27 +85,27 @@ With that configured, open a terminal to the root of your project, and run the f
<TabItem value="npm">

```bash
npx eslint . --ext .js,.jsx,.ts,.tsx
npx eslint . --ext .js,.mjs,.cjs,.jsx,.ts,.mts,.cts,.tsx
```

</TabItem>
<TabItem value="Yarn">

```bash
yarn eslint . --ext .js,.jsx,.ts,.tsx
yarn eslint . --ext .js,.mjs,.cjs,.jsx,.ts,.mts,.cts,.tsx
```

</TabItem>
</Tabs>

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"
}
}
```
Expand Down
4 changes: 2 additions & 2 deletions docs/linting/TROUBLESHOOTING.md
Expand Up @@ -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"
}
Expand Down
2 changes: 1 addition & 1 deletion packages/eslint-plugin/README.md
Expand Up @@ -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

Expand Down
Expand Up @@ -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
{
Expand All @@ -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"]
}
Expand Down
Expand Up @@ -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
{
Expand All @@ -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"]
}
Expand Down
Expand Up @@ -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
{
Expand All @@ -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"]
}
Expand Down
2 changes: 1 addition & 1 deletion packages/eslint-plugin/src/configs/eslint-recommended.ts
Expand Up @@ -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)
Expand Down
13 changes: 12 additions & 1 deletion packages/eslint-plugin/src/util/misc.ts
Expand Up @@ -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;
}

/**
Expand Down
24 changes: 14 additions & 10 deletions packages/parser/README.md
Expand Up @@ -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**.
<!-- https://github.com/microsoft/TypeScript/blob/d6e483b8dabd8fd37c00954c3f2184bb7f1eb90c/src/compiler/utilities.ts#L6281-L6285 -->

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`

Expand Down Expand Up @@ -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`

Expand Down
9 changes: 1 addition & 8 deletions packages/parser/src/parser.ts
Expand Up @@ -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) => {
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion packages/typescript-estree/README.md
Expand Up @@ -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
Expand Down
@@ -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');

Expand Down Expand Up @@ -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() {
Expand Down
@@ -1,13 +1,23 @@
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';
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
Expand Down
@@ -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');

Expand All @@ -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),
);
}

Expand Down
49 changes: 49 additions & 0 deletions 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 };
44 changes: 13 additions & 31 deletions packages/typescript-estree/src/create-program/shared.ts
Expand Up @@ -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(
Expand Down Expand Up @@ -149,7 +132,6 @@ export {
createDefaultCompilerOptionsFromExtra,
ensureAbsolutePath,
getCanonicalFileName,
getScriptKind,
getAstFromProgram,
getModuleResolver,
};

0 comments on commit 3292002

Please sign in to comment.