寫(xiě)一個(gè) Eslint 插件:Vue Template 中 Class 順序的檢查和自動(dòng)修復(fù)
有小伙伴問(wèn)我如何修復(fù) vue template 中的 class 名的順序、屬性名順序,還有 options 中的屬性順序的問(wèn)題,用 eslint 可以做到么。
答案是能,但是需要寫(xiě) eslint 插件來(lái)檢查和修復(fù)。
考慮到他可能沒(méi)有寫(xiě)過(guò) eslint 插件,所以我先把相對(duì)簡(jiǎn)單的校驗(yàn)和修復(fù) class 名的順序的插件摘出來(lái)實(shí)現(xiàn)了一下。
思路分析
首先,eslint 是否能 parse vue 的模版呢?
是可以的,因?yàn)?eslint 的 parser 支持切換,而 vue 實(shí)現(xiàn)了對(duì)應(yīng)的 parser,所以可以在 eslint 中使用 vue-eslint-parser 來(lái)解析模版。
我們可以使用 astexplorer.net 來(lái)看一下 parse 生成的 AST。
我們要處理的是 class 屬性,也就是 VAttribute 的 value 部分
可以支持傳入比較器來(lái)自定義順序,排序完之后設(shè)置回去。
當(dāng)然,vue 的模版支持 {} 來(lái)引用 data,這種我們不處理,可以過(guò)濾掉。
思路比較簡(jiǎn)單,下面我們寫(xiě)代碼來(lái)實(shí)現(xiàn)一下。
代碼實(shí)現(xiàn)
我們可以給插件起名為 vue-class-order。
首先,我們引入 eslint,設(shè)置 useEslintrc 為 false 也就是不使用配置文件,然后在 overrideConfig 屬性設(shè)置各種配置,rules 里填入這個(gè)插件。
- const { ESLint } = require("eslint");
- const engine = new ESLint({
- fix: false,
- overrideConfig: {
- parser: 'vue-eslint-parser',
- parserOptions: {
- sourceType: 'module'
- },
- rules: {
- "vue-class-order": [ "error" ]
- }
- },
- rulePaths: ['./'],
- useEslintrc: false
- });
這里的 parser 要使用 vue-eslint-parser 才可以,并且 rulePaths 也就是查找 rule 的路徑也要設(shè)置下。fix 設(shè)置為 false 代表不自動(dòng)修復(fù)。
之后,調(diào)用它的 lintText 方法來(lái)對(duì)代碼進(jìn)行 lint。
- (async function main() {
- const results = await engine.lintText(`
- <template>
- <div>
- <p class="c d e" >dongdong</p>
- <p class="c a b">guangguang</p>
- </div>
- </template>
- <script>
- export default {
- };
- </script>
- `);
- console.log(results[0].output);
- const formatter = await engine.loadFormatter("stylish");
- const resultText = formatter.format(results);
- console.log(resultText);
- })();
之后在插件里面取出來(lái):
- module.exports = {
- meta: {
- fixable: true
- },
- create(context) {
- const comparator = context.options[0];
- }
- };
這里的 comparator 就是從 context 中取出的參數(shù)。
插件的結(jié)構(gòu)是 meta,create 兩部分,meta 是各種描述插件本身的元信息,create 部分是插件的主要邏輯。
create 部分返回一個(gè) visitor,聲明對(duì)什么節(jié)點(diǎn)進(jìn)行什么操作。但是因?yàn)槲覀冇玫?parser 是 vue 自定義的(vue-eslint-parser),所以這里 visitor 也要用它提供的,也就是:
- module.exports = {
- meta: {
- fixable: true
- },
- create(context) {
- const comparator = context.options[0];
- return context.parserServices.defineTemplateBodyVisitor({
- "VAttribute[key.name=class]"(node) {
- }
- });
- }
- };
在 context.parserServices.defineTemplateBodyVisitor 方法中傳入具體的 visitor,比如我們需要對(duì) VAttribute 節(jié)點(diǎn)做處理。
eslint 支持esqury 的寫(xiě)法,也就是可以通過(guò)選擇器的方式來(lái)指定要處理的節(jié)點(diǎn),這里我們指定 key.name 為 class 的 VAttribute 節(jié)點(diǎn)
之后要拿到節(jié)點(diǎn)的值,排序一下,看看是否是對(duì)的,不對(duì)就報(bào)錯(cuò)。
- "VAttribute[key.name=class]"(node) {
- const classStr = node.value.value;
- if (!classStr.includes('{')) { //過(guò)濾掉有插值表達(dá)式的 class
- const curOrder = classStr.split(/\s/);
- const shouldOrder = [...curOrder].sort(comparator);
- if (curOrder.some((item, index) => curOrder[index] !== shouldOrder[index])) {
- context.report({
- node,
- message: 'className 順序不對(duì):' + classStr,
- loc: node.value.loc
- });
- }
- }
- }
這樣,我們就實(shí)現(xiàn)了對(duì) vue 模版中 class 的順序的 lint。
我們?cè)囈幌滦Ч?/p>
我們實(shí)現(xiàn)了對(duì) className 順序的 lint!
當(dāng)然,只報(bào)錯(cuò)不修復(fù)比較耍流氓,我們還得實(shí)現(xiàn)下自動(dòng)修復(fù)。
修復(fù)的話就是把 value 的部分替換掉,也就是拿到 value 的 range(開(kāi)始和結(jié)束的下標(biāo)),把該 range 的文本使用 fixer 的 api 替換掉。(這里要考慮引號(hào))
- context.report({
- node,
- message: 'className 順序不對(duì):' + classStr,
- loc: node.value.loc,
- *fix(fixer) {
- const [ start, end ] = node.value.range;
- yield fixer.replaceTextRange([start + 1, end - 1], shouldOrder.join(' '))
- }
- });
我們把 fixer 設(shè)置為 true,再跑一下:
做了自動(dòng)的修復(fù),沒(méi)有報(bào)錯(cuò)了!
我們實(shí)現(xiàn)了對(duì) vue 模版中 class 的順序的檢查和自動(dòng)修復(fù)!
總結(jié)
Eslint 可以基于 AST 做代碼格式的檢查和修復(fù)。
基于 AST 那就得有對(duì)應(yīng)的 parser, eslint 支持 parser 的擴(kuò)展,所以有很多 eslint parser 可用,要 parse vue 模版就可以用 vue-eslint-parser??梢杂?astexplorer.net可視化的查看。
我們要實(shí)現(xiàn)對(duì) vue 模版中 class 的順序的檢查,分析之后就是要取出 key 為 class 的 VAttribute 節(jié)點(diǎn)的 value,然后根據(jù)傳入的比較器進(jìn)行排序,如果順序不一致,就報(bào)錯(cuò)。并且還可以通過(guò) fixer 的 api 進(jìn)行自動(dòng)修復(fù),也就是對(duì)該段 range 的文本進(jìn)行替換。
這里我們通過(guò) api 來(lái)調(diào)用的 eslint,通過(guò) cli 也一樣。
這篇文章實(shí)現(xiàn)了一個(gè)相對(duì)簡(jiǎn)單的 eslint 插件,對(duì) vue template 中的代碼格式做了檢查和修復(fù),希望能夠幫助大家理清 eslint 插件開(kāi)發(fā)的思路。