Skip to content

Commit ea0fc45

Browse files
committed
[New] no-rename-default: Forbid importing a default export by a different name
1 parent e1bd0ba commit ea0fc45

17 files changed

+631
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ This change log adheres to standards from [Keep a CHANGELOG](https://keepachange
88

99
### Added
1010
- [`dynamic-import-chunkname`]: add `allowEmpty` option to allow empty leading comments ([#2942], thanks [@JiangWeixian])
11+
- [`no-rename-default`]: Forbid importing a default export by a different name ([#3006], thanks [@whitneyit])
1112

1213
### Changed
1314
- [Docs] `no-extraneous-dependencies`: Make glob pattern description more explicit ([#2944], thanks [@mulztob])

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ This plugin intends to support linting of ES2015+ (ES6+) import/export syntax, a
3737
| [no-mutable-exports](docs/rules/no-mutable-exports.md) | Forbid the use of mutable exports with `var` or `let`. | | | | | | |
3838
| [no-named-as-default](docs/rules/no-named-as-default.md) | Forbid use of exported name as identifier of default export. | | ☑️ 🚸 | | | | |
3939
| [no-named-as-default-member](docs/rules/no-named-as-default-member.md) | Forbid use of exported name as property of default export. | | ☑️ 🚸 | | | | |
40+
| [no-rename-default](docs/rules/no-rename-default.md) | Forbid importing a default export by a different name. | | 🚸 | | | | |
4041
| [no-unused-modules](docs/rules/no-unused-modules.md) | Forbid modules without exports, or exports without matching import in another module. | | | | | | |
4142

4243
### Module systems

config/warnings.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ module.exports = {
77
rules: {
88
'import/no-named-as-default': 1,
99
'import/no-named-as-default-member': 1,
10+
'import/no-rename-default': 1,
1011
'import/no-duplicates': 1,
1112
},
1213
};

docs/rules/no-rename-default.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# import/no-rename-default
2+
3+
⚠️ This rule _warns_ in the 🚸 `warnings` config.
4+
5+
<!-- end auto-generated rule header -->
6+
7+
Prohibit importing a default export by another name.
8+
9+
## Rule Details
10+
11+
Given:
12+
13+
```js
14+
// api/get-users.js
15+
export default async function getUsers() {}
16+
```
17+
18+
...this would be valid:
19+
20+
```js
21+
import getUsers from './api/get-users.js';
22+
```
23+
24+
...and the following would be reported:
25+
26+
```js
27+
// Caution: `get-users.js` has a default export `getUsers`.
28+
// This imports `getUsers` as `findUsers`.
29+
// Check if you meant to write `import getUsers from './api/get-users'` instead.
30+
import findUsers from './get-users';
31+
```

src/index.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ export const rules = {
2020
'no-named-as-default': require('./rules/no-named-as-default'),
2121
'no-named-as-default-member': require('./rules/no-named-as-default-member'),
2222
'no-anonymous-default-export': require('./rules/no-anonymous-default-export'),
23+
'no-rename-default': require('./rules/no-rename-default'),
2324
'no-unused-modules': require('./rules/no-unused-modules'),
2425

2526
'no-commonjs': require('./rules/no-commonjs'),

src/rules/no-rename-default.js

Lines changed: 217 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,217 @@
1+
/**
2+
* @fileOverview Rule to warn about importing a default export by different name
3+
* @author James Whitney
4+
*/
5+
6+
import docsUrl from '../docsUrl';
7+
import ExportMapBuilder from '../exportMap/builder';
8+
import path from 'path';
9+
10+
//------------------------------------------------------------------------------
11+
// Rule Definition
12+
//------------------------------------------------------------------------------
13+
14+
/** @type {import('@typescript-eslint/utils').TSESLint.RuleModule} */
15+
const rule = {
16+
meta: {
17+
type: 'suggestion',
18+
docs: {
19+
category: 'Helpful warnings',
20+
description: 'Forbid importing a default export by a different name.',
21+
recommended: false,
22+
url: docsUrl('no-named-as-default'),
23+
},
24+
schema: [
25+
{
26+
type: 'object',
27+
properties: {
28+
commonjs: {
29+
type: 'boolean',
30+
},
31+
},
32+
additionalProperties: false,
33+
},
34+
],
35+
},
36+
37+
create(context) {
38+
function findDefaultDestructure(properties) {
39+
const found = properties.find((property) => {
40+
if (property.key.name === 'default') {
41+
return property;
42+
}
43+
});
44+
return found;
45+
}
46+
47+
function getDefaultExportName(targetNode) {
48+
if (targetNode.type === 'CallExpression') {
49+
const [argumentNode] = targetNode.arguments;
50+
return getDefaultExportName(argumentNode);
51+
}
52+
if (targetNode.type === 'FunctionDeclaration') {
53+
return targetNode.id.name;
54+
}
55+
if (targetNode.type === 'Identifier') {
56+
return targetNode.name;
57+
}
58+
}
59+
60+
function getDefaultExportNode(exportMap) {
61+
const defaultExportNode = exportMap.exports.get('default');
62+
if (defaultExportNode == null) {
63+
return;
64+
}
65+
return defaultExportNode;
66+
}
67+
68+
function getExportMap(source, context) {
69+
const exportMap = ExportMapBuilder.get(source.value, context);
70+
if (exportMap == null) {
71+
return;
72+
}
73+
if (exportMap.errors.length > 0) {
74+
exportMap.reportErrors(context, source.value);
75+
return;
76+
}
77+
return exportMap;
78+
}
79+
80+
function handleImport(node) {
81+
82+
const exportMap = getExportMap(node.parent.source, context);
83+
if (exportMap == null) {
84+
return;
85+
}
86+
87+
const defaultExportNode = getDefaultExportNode(exportMap);
88+
if (defaultExportNode == null) {
89+
return;
90+
91+
}
92+
93+
const defaultExportName = getDefaultExportName(defaultExportNode.declaration);
94+
if (defaultExportName === undefined) {
95+
return;
96+
}
97+
98+
const importTarget = node.parent.source.value;
99+
const importBasename = path.basename(exportMap.path);
100+
101+
if (node.type === 'ImportDefaultSpecifier') {
102+
const importName = node.local.name;
103+
104+
if (importName === defaultExportName) {
105+
return;
106+
}
107+
108+
context.report({
109+
node,
110+
message: `Caution: \`${importBasename}\` has a default export \`${defaultExportName}\`. This imports \`${defaultExportName}\` as \`${importName}\`. Check if you meant to write \`import ${defaultExportName} from '${importTarget}'\` instead.`,
111+
});
112+
113+
return;
114+
}
115+
116+
if (node.type !== 'ImportSpecifier') {
117+
return;
118+
}
119+
120+
if (node.imported.name !== 'default') {
121+
return;
122+
}
123+
124+
const actualImportedName = node.local.name;
125+
126+
if (actualImportedName === defaultExportName) {
127+
return;
128+
}
129+
130+
context.report({
131+
node,
132+
message: `Caution: \`${importBasename}\` has a default export \`${defaultExportName}\`. This imports \`${defaultExportName}\` as \`${actualImportedName}\`. Check if you meant to write \`import { default as ${defaultExportName} } from '${importTarget}'\` instead.`,
133+
});
134+
}
135+
136+
function handleRequire(node) {
137+
const options = context.options[0] || {};
138+
139+
if (
140+
!options.commonjs
141+
|| node.type !== 'VariableDeclarator'
142+
|| !node.id || !(node.id.type === 'Identifier' || node.id.type === 'ObjectPattern')
143+
|| !node.init || node.init.type !== 'CallExpression'
144+
) {
145+
return;
146+
}
147+
148+
let defaultDestructure;
149+
if (node.id.type === 'ObjectPattern') {
150+
defaultDestructure = findDefaultDestructure(node.id.properties);
151+
if (defaultDestructure === undefined) {
152+
return;
153+
}
154+
}
155+
156+
const call = node.init;
157+
const [source] = call.arguments;
158+
159+
if (
160+
call.callee.type !== 'Identifier' || call.callee.name !== 'require' || call.arguments.length !== 1
161+
|| source.type !== 'Literal'
162+
) {
163+
return;
164+
}
165+
166+
const exportMap = getExportMap(source, context);
167+
if (exportMap == null) {
168+
return;
169+
}
170+
171+
const defaultExportNode = getDefaultExportNode(exportMap);
172+
if (defaultExportNode == null) {
173+
return;
174+
}
175+
176+
const defaultExportName = getDefaultExportName(defaultExportNode.declaration);
177+
const requireTarget = source.value;
178+
const requireBasename = path.basename(exportMap.path);
179+
const requireName = node.id.type === 'Identifier' ? node.id.name : defaultDestructure.value.name;
180+
181+
if (defaultExportName === undefined) {
182+
return;
183+
}
184+
185+
if (requireName === defaultExportName) {
186+
return;
187+
}
188+
189+
if (node.id.type === 'Identifier') {
190+
context.report({
191+
node,
192+
message: `Caution: \`${requireBasename}\` has a default export \`${defaultExportName}\`. This requires \`${defaultExportName}\` as \`${requireName}\`. Check if you meant to write \`const ${defaultExportName} = require('${requireTarget}')\` instead.`,
193+
});
194+
return;
195+
}
196+
197+
context.report({
198+
node,
199+
message: `Caution: \`${requireBasename}\` has a default export \`${defaultExportName}\`. This requires \`${defaultExportName}\` as \`${requireName}\`. Check if you meant to write \`const { default: ${defaultExportName} } = require('${requireTarget}')\` instead.`,
200+
});
201+
}
202+
203+
return {
204+
ImportDefaultSpecifier(node) {
205+
handleImport(node);
206+
},
207+
ImportSpecifier(node) {
208+
handleImport(node);
209+
},
210+
VariableDeclarator(node) {
211+
handleRequire(node);
212+
},
213+
};
214+
},
215+
};
216+
217+
module.exports = rule;
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export default {};
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
export const barNamed1 = 'bar-named-1';
2+
export const barNamed2 = 'bar-named-2';
3+
4+
const bar = 'bar';
5+
6+
export default bar;
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
export const fooNamed1 = 'foo-named-1';
2+
export const fooNamed2 = 'foo-named-2';
3+
4+
const foo = 'foo';
5+
6+
export default foo;
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export default function getUsersSync() {}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export default async function getUsers() {}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export default 123;
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import getUsers from '../default-fn-get-users';
2+
import withAuth from './hoc-with-auth';
3+
import withLogger from './hoc-with-logger';
4+
5+
export default withLogger(withAuth(getUsers));
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
import getUsers from '../default-fn-get-users';
2+
import withLogger from './hoc-with-logger';
3+
4+
export default withLogger(getUsers);
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
export default function withAuth(fn) {
2+
return function innerAuth(...args) {
3+
const auth = {};
4+
return fn.call(null, auth, ...args);
5+
}
6+
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
export default function withLogger(fn) {
2+
return function innerLogger(...args) {
3+
console.log(`${fn.name} called`);
4+
return fn.apply(null, args);
5+
}
6+
}

0 commit comments

Comments
 (0)