Skip to content
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

Fix 1786 #1831

Merged
merged 15 commits into from Apr 12, 2022
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/rules/README.md
Expand Up @@ -12,6 +12,7 @@ sidebarDepth: 0
:bulb: Indicates that some problems reported by the rule are manually fixable by editor [suggestions](https://eslint.org/docs/developer-guide/working-with-rules#providing-suggestions).
:::


## Base Rules (Enabling Correct ESLint Parsing)

Enforce all the rules in this category, as well as all higher priority rules, with:
Expand Down Expand Up @@ -317,6 +318,7 @@ For example:
| [vue/html-comment-content-spacing](./html-comment-content-spacing.md) | enforce unified spacing in HTML comments | :wrench: |
| [vue/html-comment-indent](./html-comment-indent.md) | enforce consistent indentation in HTML comments | :wrench: |
| [vue/match-component-file-name](./match-component-file-name.md) | require component name property to match its file name | |
| [vue/match-component-import-name](./match-component-import-name.md) | require the registered component name to match the imported component name | |
| [vue/new-line-between-multi-line-property](./new-line-between-multi-line-property.md) | enforce new lines between multi-line properties in Vue components | :wrench: |
| [vue/next-tick-style](./next-tick-style.md) | enforce Promise or callback style in `nextTick` | :wrench: |
| [vue/no-bare-strings-in-template](./no-bare-strings-in-template.md) | disallow the use of bare strings in `<template>` | |
Expand Down
102 changes: 102 additions & 0 deletions docs/rules/match-component-import-name.md
@@ -0,0 +1,102 @@
---
pageClass: rule-details
sidebarDepth: 0
title: vue/match-component-import-name
description: require the registered component name to match the imported component name
---

# vue/match-component-import-name

> require the registered component name to match the imported component name

- :exclamation: <badge text="This rule has not been released yet." vertical="middle" type="error"> **_This rule has not been released yet._** </badge>

This rule reports if the name of a registered component does not match its imported name.

- :exclamation: <badge text="This rule has not been released yet." vertical="middle" type="error"> **_This rule has not been released yet._** </badge>
doug-wade marked this conversation as resolved.
Show resolved Hide resolved

## :book: Rule Details

This rule has some options.

```json
{
"vue/match-component-import-name": [
"error",
{
"prefix": "prefix-",
"case": "kebab-case"
FloEdelmann marked this conversation as resolved.
Show resolved Hide resolved
}
]
}
```
FloEdelmann marked this conversation as resolved.
Show resolved Hide resolved

By default, this rule will validate that the imported name is the same casing.

Case can be one of: `"kebab-case"` or `"PascalCase"`

An optional prefix can be provided that must be prepended to all imports.

If you are not registering components, this rule will be ignored.

<eslint-code-block :rules="{'vue/match-component-file-name': ['error']}">

```javascript
/* ✓ GOOD */
export default { components: { AppButton } }

/* ✗ BAD */
export default { components: { SomeOtherName: AppButton } }
export default { components: { 'app-button': AppButton } }
```

</eslint-code-block>

<eslint-code-block :rules="{'vue/match-component-file-name': ['error', { case: 'kebab-case' }]}">

```javascript
/* ✓ GOOD */
export default { components: { 'app-button': AppButton } }

/* ✗ BAD */
export default { components: { SomeOtherName: AppButton } }
export default { components: { AppButton } }
```
doug-wade marked this conversation as resolved.
Show resolved Hide resolved

</eslint-code-block>

<eslint-code-block :rules="{'vue/match-component-file-name': ['error', { prefix: 'Prefix' }]}">

```javascript
/* ✓ GOOD */
export default { components: { PrefixAppButton: AppButton } }

/* ✗ BAD */
export default { components: { SomeOtherName: AppButton } }
export default { components: { 'app-button': AppButton } }
export default { components: { 'prefix-app-button': PrefixAppButton } }
```
doug-wade marked this conversation as resolved.
Show resolved Hide resolved

</eslint-code-block>

## :wrench: Options

```json
{
"vue/match-component-import-name": [
"error",
{
"prefix": "prefix-",
"case": "kebab-case"
}
]
}
```

- `"prefix": ""` ... array of file extensions to be verified. Default is set to the empty string.
- `"case": "PascalCase"` ... one of "kebab-case" or "PascalCase", indicating the casing of the registered name. Default is set to `PascalCase`.

## :mag: Implementation

- [Rule source](https://github.com/vuejs/eslint-plugin-vue/blob/master/lib/rules/match-component-import-name.js)
- [Test source](https://github.com/vuejs/eslint-plugin-vue/blob/master/tests/lib/rules/match-component-import-name.js)
1 change: 1 addition & 0 deletions lib/index.js
Expand Up @@ -47,6 +47,7 @@ module.exports = {
'key-spacing': require('./rules/key-spacing'),
'keyword-spacing': require('./rules/keyword-spacing'),
'match-component-file-name': require('./rules/match-component-file-name'),
'match-component-import-name': require('./rules/match-component-import-name'),
'max-attributes-per-line': require('./rules/max-attributes-per-line'),
'max-len': require('./rules/max-len'),
'multi-word-component-names': require('./rules/multi-word-component-names'),
Expand Down
123 changes: 123 additions & 0 deletions lib/rules/match-component-import-name.js
@@ -0,0 +1,123 @@
/**
* @author Doug Wade <douglas.b.wade@gmail.com>
* See LICENSE file in root directory for full license.
*/
'use strict'

const utils = require('../utils')
const casing = require('../utils/casing')

module.exports = {
meta: {
type: 'problem',
docs: {
description:
'require the registered component name to match the imported component name',
categories: undefined,
url: ''
},
fixable: null,
schema: [
{
type: 'object',
properties: {
prefix: {
type: 'string'
},
casing: {
type: 'string'
}
},
additionalProperties: false
}
],
messages: {
unexpected:
'component alias {{importedName}} should match {{expectedName}}'
}
},
/** @param {RuleContext} context */
create(context) {
const options = context.options[0] || {}

/**
* @param {ExportDefaultDeclaration} node
* @return {Array<Property>}
*/
function getComponents(node) {
if (node.declaration.type !== 'ObjectExpression') {
return []
}

const componentProperty = node.declaration.properties
.filter(utils.isProperty)
.filter((property) => {
return utils.getStaticPropertyName(property) === 'components'
})[0]
doug-wade marked this conversation as resolved.
Show resolved Hide resolved

if (
!componentProperty ||
componentProperty.value.type !== 'ObjectExpression'
) {
return []
}

return componentProperty.value.properties.filter(utils.isProperty)
}

/** @param {Property} property */
function propertyStartsWithPrefix(property) {
if (!options.prefix) {
return true
}

const name = utils.getStaticPropertyName(property)
return name ? name.startsWith(options.prefix) : false
}

return utils.defineScriptVisitor(context, {
ExportDefaultDeclaration(node) {
const components = getComponents(node)

if (!components) {
return
}

components.forEach(
/** @param {Property} property */
(property) => {
if (!propertyStartsWithPrefix(property)) {
context.report({
node: property,
message: `component alias ${utils.getStaticPropertyName(
property
)} should have the prefix ${options.prefix}`
})
}

if (property.value.type !== 'Identifier') {
return
}

const prefix = options.prefix || ''
const importedName = utils.getStaticPropertyName(property) || ''
const expectedName =
options.casing === 'kebab-case'
? prefix + casing.kebabCase(property.value.name)
: prefix + casing.pascalCase(property.value.name)
if (importedName !== expectedName) {
context.report({
node: property,
messageId: 'unexpected',
data: {
importedName,
expectedName
}
})
}
}
)
}
})
}
}
74 changes: 74 additions & 0 deletions lib/utils/index.js
Expand Up @@ -1015,6 +1015,12 @@ module.exports = {
* @returns {VElement | null} the element of `<script setup>`
*/
getScriptSetupElement,
/**
* Gets the element of `<script>` that is NOT setup
* @param {RuleContext} context The ESLint rule context object.
* @returns {VElement | null} the element of `<script>`
*/
getScriptElement,
FloEdelmann marked this conversation as resolved.
Show resolved Hide resolved

/**
* Check if current file is a Vue instance or component and call callback
Expand Down Expand Up @@ -1273,6 +1279,48 @@ module.exports = {
return scriptSetupVisitor
},

/**
* Define handlers to traverse the AST nodes in `<script>`.
*
* @param {RuleContext} context The ESLint rule context object.
* @param {ScriptSetupVisitor} visitor The visitor to traverse the AST nodes.
*/
defineScriptVisitor(context, visitor) {
const script = getScriptElement(context)
if (script == null) {
return {}
}
const scriptRange = script.range

/**
* @param {ESNode} node
*/
function inScript(node) {
return scriptRange[0] <= node.range[0] && node.range[1] <= scriptRange[1]
}
/**
* @param {string} key
* @param {ESNode} node
* @param {any[]} args
*/
function callVisitor(key, node, ...args) {
if (visitor[key]) {
if (inScript(node)) {
// @ts-expect-error
visitor[key](node, ...args)
}
}
}

/** @type {NodeListener} */
const scriptVisitor = {}
for (const key in visitor) {
scriptVisitor[key] = (node) => callVisitor(key, node)
}

return scriptVisitor
},

/**
* Checks whether given defineProps call node has withDefaults.
* @param {CallExpression} node The node of defineProps
Expand Down Expand Up @@ -2409,6 +2457,32 @@ function getScriptSetupElement(context) {
return null
}

/**
* Gets the element of `<script>` that is NOT setup
* @param {RuleContext} context The ESLint rule context object.
* @returns {VElement | null} the elements of `<script>`
*/
function getScriptElement(context) {
const df =
context.parserServices.getDocumentFragment &&
context.parserServices.getDocumentFragment()
if (!df) {
return null
}
const scripts = df.children
.filter(isVElement)
.filter((e) => e.name === 'script')
if (scripts.length === 2) {
return scripts.find((e) => !hasAttribute(e, 'setup')) || null
} else {
const script = scripts[0]
if (script && !hasAttribute(script, 'setup')) {
return script
}
}
return null
}

/**
* Check whether the given node is a Vue component based
* on the filename and default export type
Expand Down