Prerequisities
- A project with Vue and your own ESLint rule
The problem
Sometimes, we’d like to write our own custom ESLint rules for our Vue projects, for example if we like code to be written in a certain way inside the team.
Now sometimes you for example want something else to happen when you introduce a certain component into your Vue template. In that case, this code is for you:
const utils = require('eslint-plugin-vue/lib/utils')
const MyComponent = 'radiocard'
module.exports = {
meta: {
type: 'problem',
docs: {
description: 'This component is not allowed',
},
},
create(context) {
return utils.defineTemplateBodyVisitor(context, {
VElement(node) {
// node.name format is all lowercase
// node.rawName is MyComponent format
if (node.name === MyComponent) {
// Do something fun
}
},
})
},
}
In this case, we have a component named RadioCard
in our template,
and through node.name
or node.rawName
we can find this component.
Make sure to use node.rawName
if you want to find it by RadioCard
and
not radiocard
.
Wrapup
In this post we’ve examined how to find a Vue component in your own ESLint rule.