我正在使用vue-eslint-parser
编写esint规则。需要来防止功能组件使用vuetemplate
语法。
我已经写了一条禁止语法<template functional>
:的规则
create(context) {
return context.parserServices.defineDocumentVisitor(
{
VDocumentFragment(node) {
const template = node.children.find(item => item.type === 'VElement' && item.name === 'template');
if (!template) return;
const functionalAttr = template.startTag.attributes.find(item => !item.directive && item.key.name === 'functional');
if (functionalAttr) {
context.report({
message: "Don't use vue templates with functional components",
loc: node.loc
});
}
}
}
);
}
问题:如何使以下代码也无效?(换句话说,如何检查script
标签及其内部的代码(。
<template>
</template>
<script>
export default {
functional: true,
};
</script>
谢谢!
链接到我找到解决方案的文档(不太清楚(:
create(context: Rule.RuleContext) {
return context.parserServices.defineTemplateBodyVisitor(
{
VElement(node: VElement): void {
if (node.name !== 'template') return;
const functionalAttr = node.startTag.attributes.find(item => !item.directive && item.key.name === 'functional');
if (functionalAttr) {
context.report({
message: "Don't use 'functional' attribute in vue templates. Use render function instead of vue templates for functional components.",
loc: node.loc
});
}
}
},
{
Program(node: ESLintProgram): void {
if (!node.templateBody) return;
const targetNode = node.body.find(item => item.type === 'ExportDefaultDeclaration') as ExportDefaultDeclaration || undefined;
if (!targetNode) return;
const functionalOption = (targetNode.declaration as ObjectExpression).properties.find(item => item.type === 'Property' && (item.key as Identifier).name === 'functional');
if (functionalOption) {
context.report({
message: "Don't use 'functional' property along with vue templates. Use render function instead of vue templates for functional components.",
loc: node.loc
});
}
}
}
);
}