-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
no-typescript-default-import.ts
78 lines (73 loc) · 2.53 KB
/
no-typescript-default-import.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
import type { TSESTree } from '@typescript-eslint/utils';
import { AST_NODE_TYPES } from '@typescript-eslint/utils';
import { createRule } from '../util';
/*
We have `allowSyntheticDefaultImports` turned on in this project, so there are two problems that arise:
- TypeScript's auto import will suggest `import ts = require('typescript');` if you type `ts`
- VSCode's suggestion feature will suggest changing `import * as ts from 'typescript'` to `import ts from 'typescript'`
In order to keep compatibility with a wide range of consumers, some of whom don't use `allowSyntheticDefaultImports`, we should
always use either:
- `import * as ts from 'typescript';`
- `import { SyntaxKind } from 'typescript';`
*/
export default createRule({
name: 'no-typescript-default-import',
meta: {
type: 'problem',
docs: {
description:
"Enforce that packages rules don't do `import ts from 'typescript';`",
recommended: 'error',
},
fixable: 'code',
schema: [],
messages: {
noTSDefaultImport: [
"Do not use the default import for typescript. Doing so will cause the package's type definitions to do the same.",
"This causes errors for consumers if they don't use the allowSyntheticDefaultImports compiler option.",
].join('\n'),
},
},
defaultOptions: [],
create(context) {
return {
'ImportDeclaration > ImportDefaultSpecifier'(
node: TSESTree.ImportDefaultSpecifier,
): void {
const importStatement = node.parent as TSESTree.ImportDeclaration;
if (importStatement.source.value === 'typescript') {
context.report({
node,
messageId: 'noTSDefaultImport',
fix(fixer) {
if (importStatement.specifiers.length === 1) {
return fixer.replaceText(node, '* as ts');
}
return null;
},
});
}
},
'TSImportEqualsDeclaration > TSExternalModuleReference'(
node: TSESTree.TSExternalModuleReference,
): void {
const parent = node.parent as TSESTree.TSImportEqualsDeclaration;
if (
node.expression.type === AST_NODE_TYPES.Literal &&
node.expression.value === 'typescript'
) {
context.report({
node,
messageId: 'noTSDefaultImport',
fix(fixer) {
return fixer.replaceText(
parent,
"import * as ts from 'typescript';",
);
},
});
}
},
};
},
});