-
-
Notifications
You must be signed in to change notification settings - Fork 385
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add no-anonymous-default-export
rule
#2273
Merged
sindresorhus
merged 25 commits into
sindresorhus:main
from
fisker:no-anonymous-default-export
Feb 9, 2024
Merged
Changes from all commits
Commits
Show all changes
25 commits
Select commit
Hold shift + click to select a range
bb56398
Add tests
fisker 7162ebf
Implement
fisker 569b536
Better location
fisker 414d858
Suggestion
fisker 13c4d11
Suggestion for function
fisker 8e48b4c
Arrow function
fisker 1d36811
decorator
fisker 139634a
Docs / lints
fisker bbf771a
More tests
fisker 3471bd4
Linting
fisker c886c20
Test super class
fisker a2a3ff7
Update no-anonymous-default-export.md
fisker 266ce9f
Prepare for `cjs`
fisker c70f9b0
Support `ClassExpression` & `FunctionExpression`
fisker 9a5f276
Support `module.exports =` and `exports =`
fisker cd95e26
Remove name in error message
fisker 5922bd2
Fix Parenthesized assignment
fisker 03c9c96
Only check expressions
fisker df2b860
Linting
fisker eb78a88
Fix codebase
fisker 0e2927a
More tests
fisker 3b52c8a
Improve fix
fisker a8a968e
linting
fisker 3d73e06
Check parent type instead
fisker 6ff9e91
Update no-anonymous-default-export.md
sindresorhus File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
# Disallow anonymous functions and classes as the default export | ||
|
||
💼 This rule is enabled in the ✅ `recommended` [config](https://github.com/sindresorhus/eslint-plugin-unicorn#preset-configs). | ||
|
||
💡 This rule is manually fixable by [editor suggestions](https://eslint.org/docs/developer-guide/working-with-rules#providing-suggestions). | ||
|
||
<!-- end auto-generated rule header --> | ||
<!-- Do not manually modify this header. Run: `npm run fix:eslint-docs` --> | ||
|
||
Naming default exports improves codebase searchability by ensuring consistent identifier use for a module's default export, both where it's declared and where it's imported. | ||
|
||
## Fail | ||
|
||
```js | ||
export default class {} | ||
``` | ||
|
||
```js | ||
export default function () {} | ||
``` | ||
|
||
```js | ||
export default () => {}; | ||
``` | ||
|
||
```js | ||
module.exports = class {}; | ||
``` | ||
|
||
```js | ||
module.exports = function () {}; | ||
``` | ||
|
||
```js | ||
module.exports = () => {}; | ||
``` | ||
|
||
## Pass | ||
|
||
```js | ||
export default class Foo {} | ||
``` | ||
|
||
```js | ||
export default function foo () {} | ||
``` | ||
|
||
```js | ||
const foo = () => {}; | ||
export default foo; | ||
``` | ||
|
||
```js | ||
module.exports = class Foo {}; | ||
``` | ||
|
||
```js | ||
module.exports = function foo () {}; | ||
``` | ||
|
||
```js | ||
const foo = () => {}; | ||
module.exports = foo; | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -134,7 +134,8 @@ | |
] | ||
} | ||
], | ||
"import/order": "off" | ||
"import/order": "off", | ||
"func-names": "off" | ||
}, | ||
"overrides": [ | ||
{ | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,212 @@ | ||
'use strict'; | ||
|
||
const path = require('node:path'); | ||
const { | ||
getFunctionHeadLocation, | ||
getFunctionNameWithKind, | ||
isOpeningParenToken, | ||
} = require('@eslint-community/eslint-utils'); | ||
const { | ||
isIdentifierName, | ||
} = require('@babel/helper-validator-identifier'); | ||
const getClassHeadLocation = require('./utils/get-class-head-location.js'); | ||
const {upperFirst, camelCase} = require('./utils/lodash.js'); | ||
const {getParenthesizedRange} = require('./utils/parentheses.js'); | ||
const { | ||
getScopes, | ||
avoidCapture, | ||
} = require('./utils/index.js'); | ||
const {isMemberExpression} = require('./ast/index.js'); | ||
|
||
const MESSAGE_ID_ERROR = 'no-anonymous-default-export/error'; | ||
const MESSAGE_ID_SUGGESTION = 'no-anonymous-default-export/suggestion'; | ||
const messages = { | ||
[MESSAGE_ID_ERROR]: 'The {{description}} should be named.', | ||
[MESSAGE_ID_SUGGESTION]: 'Name it as `{{name}}`.', | ||
}; | ||
|
||
const isClassKeywordToken = token => token.type === 'Keyword' && token.value === 'class'; | ||
const isAnonymousClassOrFunction = node => | ||
( | ||
( | ||
node.type === 'FunctionDeclaration' | ||
|| node.type === 'FunctionExpression' | ||
|| node.type === 'ClassDeclaration' | ||
|| node.type === 'ClassExpression' | ||
) | ||
&& !node.id | ||
) | ||
|| node.type === 'ArrowFunctionExpression'; | ||
|
||
function getSuggestionName(node, filename, sourceCode) { | ||
if (filename === '<input>' || filename === '<text>') { | ||
return; | ||
} | ||
|
||
let [name] = path.basename(filename).split('.'); | ||
name = camelCase(name); | ||
|
||
if (!isIdentifierName(name)) { | ||
return; | ||
} | ||
|
||
name = node.type === 'ClassDeclaration' ? upperFirst(name) : name; | ||
name = avoidCapture(name, getScopes(sourceCode.getScope(node))); | ||
|
||
return name; | ||
} | ||
|
||
function addName(fixer, node, name, sourceCode) { | ||
switch (node.type) { | ||
case 'ClassDeclaration': | ||
case 'ClassExpression': { | ||
const lastDecorator = node.decorators?.at(-1); | ||
const classToken = lastDecorator | ||
? sourceCode.getTokenAfter(lastDecorator, isClassKeywordToken) | ||
: sourceCode.getFirstToken(node, isClassKeywordToken); | ||
return fixer.insertTextAfter(classToken, ` ${name}`); | ||
} | ||
|
||
case 'FunctionDeclaration': | ||
case 'FunctionExpression': { | ||
const openingParenthesisToken = sourceCode.getFirstToken( | ||
node, | ||
isOpeningParenToken, | ||
); | ||
return fixer.insertTextBefore( | ||
openingParenthesisToken, | ||
`${sourceCode.text.charAt(openingParenthesisToken.range[0] - 1) === ' ' ? '' : ' '}${name} `, | ||
); | ||
} | ||
|
||
case 'ArrowFunctionExpression': { | ||
const [exportDeclarationStart, exportDeclarationEnd] | ||
= node.parent.type === 'ExportDefaultDeclaration' | ||
? node.parent.range | ||
: node.parent.parent.range; | ||
const [arrowFunctionStart, arrowFunctionEnd] = getParenthesizedRange(node, sourceCode); | ||
|
||
let textBefore = sourceCode.text.slice(exportDeclarationStart, arrowFunctionStart); | ||
let textAfter = sourceCode.text.slice(arrowFunctionEnd, exportDeclarationEnd); | ||
|
||
textBefore = `\n${textBefore}`; | ||
if (!/\s$/.test(textBefore)) { | ||
textBefore = `${textBefore} `; | ||
} | ||
|
||
if (!textAfter.endsWith(';')) { | ||
textAfter = `${textAfter};`; | ||
} | ||
|
||
return [ | ||
fixer.replaceTextRange( | ||
[exportDeclarationStart, arrowFunctionStart], | ||
`const ${name} = `, | ||
), | ||
fixer.replaceTextRange( | ||
[arrowFunctionEnd, exportDeclarationEnd], | ||
';', | ||
), | ||
fixer.insertTextAfterRange( | ||
[exportDeclarationEnd, exportDeclarationEnd], | ||
`${textBefore}${name}${textAfter}`, | ||
), | ||
]; | ||
} | ||
|
||
// No default | ||
} | ||
} | ||
|
||
function getProblem(node, context) { | ||
const {sourceCode, physicalFilename} = context; | ||
|
||
const suggestionName = getSuggestionName(node, physicalFilename, sourceCode); | ||
|
||
let loc; | ||
let description; | ||
if (node.type === 'ClassDeclaration' || node.type === 'ClassExpression') { | ||
loc = getClassHeadLocation(node, sourceCode); | ||
description = 'class'; | ||
} else { | ||
loc = getFunctionHeadLocation(node, sourceCode); | ||
// [TODO: @fisker]: Ask `@eslint-community/eslint-utils` to expose `getFunctionKind` | ||
const nameWithKind = getFunctionNameWithKind(node); | ||
description = nameWithKind.replace(/ '.*?'$/, ''); | ||
} | ||
|
||
const problem = { | ||
node, | ||
loc, | ||
messageId: MESSAGE_ID_ERROR, | ||
data: { | ||
description, | ||
}, | ||
}; | ||
|
||
if (!suggestionName) { | ||
return problem; | ||
} | ||
|
||
problem.suggest = [ | ||
{ | ||
messageId: MESSAGE_ID_SUGGESTION, | ||
data: { | ||
name: suggestionName, | ||
}, | ||
fix: fixer => addName(fixer, node, suggestionName, sourceCode), | ||
}, | ||
]; | ||
|
||
return problem; | ||
} | ||
|
||
/** @param {import('eslint').Rule.RuleContext} context */ | ||
const create = context => { | ||
context.on('ExportDefaultDeclaration', node => { | ||
if (!isAnonymousClassOrFunction(node.declaration)) { | ||
return; | ||
} | ||
|
||
return getProblem(node.declaration, context); | ||
}); | ||
|
||
context.on('AssignmentExpression', node => { | ||
if ( | ||
!isAnonymousClassOrFunction(node.right) | ||
|| !( | ||
node.parent.type === 'ExpressionStatement' | ||
&& node.parent.expression === node | ||
) | ||
|| !( | ||
isMemberExpression(node.left, { | ||
object: 'module', | ||
property: 'exports', | ||
computed: false, | ||
optional: false, | ||
}) | ||
|| ( | ||
node.left.type === 'Identifier', | ||
node.left.name === 'exports' | ||
) | ||
) | ||
) { | ||
return; | ||
} | ||
|
||
return getProblem(node.right, context); | ||
}); | ||
}; | ||
|
||
/** @type {import('eslint').Rule.RuleModule} */ | ||
module.exports = { | ||
create, | ||
meta: { | ||
type: 'suggestion', | ||
docs: { | ||
description: 'Disallow anonymous functions and classes as the default export.', | ||
}, | ||
hasSuggestions: true, | ||
messages, | ||
}, | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,7 @@ | ||
'use strict'; | ||
|
||
module.exports = string => string.replaceAll( | ||
const escapeTemplateElementRaw = string => string.replaceAll( | ||
/(?<=(?:^|[^\\])(?:\\\\)*)(?<symbol>(?:`|\$(?={)))/g, | ||
'\\$<symbol>', | ||
); | ||
module.exports = escapeTemplateElementRaw; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,8 @@ | ||
'use strict'; | ||
|
||
// Get identifiers of given variable | ||
module.exports = ({identifiers, references}) => [...new Set([ | ||
const getVariableIdentifiers = ({identifiers, references}) => [...new Set([ | ||
...identifiers, | ||
...references.map(({identifier}) => identifier), | ||
])]; | ||
module.exports = getVariableIdentifiers; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,8 @@ | ||
'use strict'; | ||
|
||
module.exports = (node1, node2) => | ||
const hasSameRange = (node1, node2) => | ||
node1 | ||
&& node2 | ||
&& node1.range[0] === node2.range[0] | ||
&& node1.range[1] === node2.range[1]; | ||
module.exports = hasSameRange; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This rule not allow