-
-
Notifications
You must be signed in to change notification settings - Fork 679
feat: add no-required-prop-with-default
rule
#1943
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
Merged
Merged
Changes from 4 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
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 hidden or 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 hidden or 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,95 @@ | ||
--- | ||
pageClass: rule-details | ||
sidebarDepth: 0 | ||
title: vue/no-required-prop-with-default | ||
description: enforce props with default values to be optional | ||
--- | ||
# vue/no-required-prop-with-default | ||
|
||
> enforce props with default values to be optional | ||
|
||
- :exclamation: <badge text="This rule has not been released yet." vertical="middle" type="error"> ***This rule has not been released yet.*** </badge> | ||
- :wrench: The `--fix` option on the [command line](https://eslint.org/docs/user-guide/command-line-interface#fixing-problems) can automatically fix some of the problems reported by this rule. | ||
|
||
## :book: Rule Details | ||
|
||
If a prop is declared with a default value, whether it is required or not, we can always skip it in actual use. In that situation, the default value would be applied. | ||
So, a required prop with a default value is essentially the same as an optional prop. | ||
This rule enforces all props with default values to be optional. | ||
|
||
<eslint-code-block fix :rules="{'vue/no-required-prop-with-default': ['error', { autoFix: true }]}"> | ||
|
||
```vue | ||
<script setup lang="ts"> | ||
/* ✓ GOOD */ | ||
const props = withDefaults( | ||
defineProps<{ | ||
name?: string | number | ||
age?: number | ||
}>(), | ||
{ | ||
name: "Foo", | ||
} | ||
); | ||
|
||
/* ✗ BAD */ | ||
const props = withDefaults( | ||
defineProps<{ | ||
name: string | number | ||
age?: number | ||
}>(), | ||
{ | ||
name: "Foo", | ||
} | ||
); | ||
</script> | ||
``` | ||
|
||
</eslint-code-block> | ||
|
||
<eslint-code-block fix :rules="{'vue/no-required-prop-with-default': ['error', { autoFix: true }]}"> | ||
|
||
```vue | ||
<script> | ||
export default { | ||
/* ✓ GOOD */ | ||
props: { | ||
name: { | ||
required: true, | ||
default: 'Hello' | ||
} | ||
} | ||
|
||
/* ✗ BAD */ | ||
props: { | ||
name: { | ||
required: true, | ||
default: 'Hello' | ||
} | ||
} | ||
} | ||
</script> | ||
``` | ||
|
||
</eslint-code-block> | ||
|
||
## :wrench: Options | ||
|
||
```json | ||
{ | ||
"vue/no-required-prop-with-default": ["error", { | ||
"autofix": false, | ||
}] | ||
} | ||
``` | ||
|
||
- `"autofix"` ... If `true`, enable autofix. (Default: `false`) | ||
|
||
## :couple: Related Rules | ||
|
||
- [vue/require-default-prop](./require-default-prop.md) | ||
|
||
## :mag: Implementation | ||
|
||
- [Rule source](https://github.com/vuejs/eslint-plugin-vue/blob/master/lib/rules/no-required-prop-with-default.js) | ||
- [Test source](https://github.com/vuejs/eslint-plugin-vue/blob/master/tests/lib/rules/no-required-prop-with-default.js) |
This file contains hidden or 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 hidden or 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,148 @@ | ||
/** | ||
* @author @neferqiqi | ||
* See LICENSE file in root directory for full license. | ||
*/ | ||
'use strict' | ||
// ------------------------------------------------------------------------------ | ||
// Requirements | ||
// ------------------------------------------------------------------------------ | ||
|
||
const utils = require('../utils') | ||
/** | ||
* @typedef {import('../utils').ComponentTypeProp} ComponentTypeProp | ||
*/ | ||
|
||
// ------------------------------------------------------------------------------ | ||
// Rule Definition | ||
// ------------------------------------------------------------------------------ | ||
|
||
module.exports = { | ||
meta: { | ||
type: 'problem', | ||
docs: { | ||
description: 'enforce props with default values to be optional', | ||
categories: undefined, | ||
url: 'https://eslint.vuejs.org/rules/no-required-prop-with-default.html' | ||
}, | ||
fixable: 'code', | ||
schema: [ | ||
{ | ||
type: 'object', | ||
properties: { | ||
autofix: { | ||
type: 'boolean' | ||
} | ||
}, | ||
additionalProperties: false | ||
} | ||
], | ||
messages: { | ||
// ... | ||
} | ||
}, | ||
/** @param {RuleContext} context */ | ||
create(context) { | ||
/** | ||
* @param {ComponentTypeProp} prop | ||
* @param {Token[]} tokens | ||
* */ | ||
const findKeyToken = (prop, tokens) => | ||
tokens.find((token) => { | ||
const isKeyIdentifierEqual = | ||
prop.key.type === 'Identifier' && token.value === prop.key.name | ||
const isKeyLiteralEqual = | ||
prop.key.type === 'Literal' && token.value === prop.key.raw | ||
return isKeyIdentifierEqual || isKeyLiteralEqual | ||
}) | ||
|
||
let canAutoFix = false | ||
const option = context.options[0] | ||
if (option) { | ||
canAutoFix = option.autofix | ||
} | ||
|
||
return utils.compositingVisitors( | ||
utils.defineVueVisitor(context, { | ||
onVueObjectEnter(node) { | ||
utils.getComponentPropsFromOptions(node).map((prop) => { | ||
if ( | ||
prop.type === 'object' && | ||
prop.propName && | ||
prop.value.type === 'ObjectExpression' && | ||
utils.findProperty(prop.value, 'default') | ||
) { | ||
const requiredProperty = utils.findProperty( | ||
prop.value, | ||
'required' | ||
) | ||
if (!requiredProperty) return | ||
const requiredNode = requiredProperty.value | ||
if ( | ||
requiredNode && | ||
requiredNode.type === 'Literal' && | ||
!!requiredNode.value | ||
) { | ||
context.report({ | ||
node: prop.node, | ||
loc: prop.node.loc, | ||
data: { | ||
key: prop.propName | ||
}, | ||
message: `Prop "{{ key }}" should be optional.`, | ||
fix: canAutoFix | ||
? (fixer) => fixer.replaceText(requiredNode, 'false') | ||
: null | ||
}) | ||
} | ||
} | ||
}) | ||
} | ||
}), | ||
utils.defineScriptSetupVisitor(context, { | ||
onDefinePropsEnter(node, props) { | ||
if (!utils.hasWithDefaults(node)) { | ||
return | ||
} | ||
const withDefaultsProps = Object.keys( | ||
utils.getWithDefaultsPropExpressions(node) | ||
) | ||
const requiredProps = props.flatMap((item) => | ||
item.type === 'type' && item.required ? [item] : [] | ||
) | ||
|
||
for (const prop of requiredProps) { | ||
if (withDefaultsProps.includes(prop.propName)) { | ||
const firstToken = context | ||
.getSourceCode() | ||
.getFirstToken(prop.node) | ||
// skip setter & getter case | ||
if (firstToken.value === 'get' || firstToken.value === 'set') { | ||
ota-meshi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return | ||
} | ||
// skip computed | ||
if (prop.node.computed) { | ||
return | ||
} | ||
const keyToken = findKeyToken( | ||
prop, | ||
context.getSourceCode().getTokens(prop.node) | ||
) | ||
if (!keyToken) return | ||
context.report({ | ||
node: prop.node, | ||
loc: prop.node.loc, | ||
data: { | ||
key: prop.propName | ||
}, | ||
message: `Prop "{{ key }}" should be optional.`, | ||
fix: canAutoFix | ||
? (fixer) => fixer.insertTextAfter(keyToken, '?') | ||
ota-meshi marked this conversation as resolved.
Show resolved
Hide resolved
|
||
: null | ||
}) | ||
} | ||
} | ||
} | ||
}) | ||
) | ||
} | ||
} |
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.
Uh oh!
There was an error while loading. Please reload this page.