在公司实习时遇到了一个问题,我们会用i18n来去做网站的中英文转换,我们并且会写一份json来管理我们所有的key,但会遇到一个问题就是说如果一个key在英文有定义,但是在中文没有定义的话,他不会有自动检查报错的功能,导致我们没有办法在commit的时候知道key键有缺失,思来想去可以用两个方法来做
用pre-commit执行一个script把我们想要的规则写成一个Eslint Rule,这样在commit时就会去检查key键的缺失最后我选定了第二种方法,原因是公司的Project很大,而我们希望去实作的网站算是其中的一部分,如果为了一个小型的检查在整体的pre-commit.yml上加一条规则我会觉得对专案的维护是不利的,于是便开始搜寻了解如何去实作一个Eslint Rule
因为公司的前端是使用TypeScript,所以我的Plugins也是使用TypeScript,
接下来会教大家如何建立一个基本的TypeScript Eslint Plugins
mkdir eslint-plugin-my-rulecd eslint-plugin-my-rulenpm init
记得一定要将Package Name 定义成 eslint-plugin-xxx 格式的{ "name": "eslint-plugin-my-rule", ...
安装相关套件npm i -D @types/eslint @types/node tsup typescript
我们会把档案分成src跟dist,dist为我们之后typescript转换之后存放的位置
接着在Package.json中加入如下,main为插件的加载点,files为指定发布套件后要放入的的档案或是目录,
{ "name": "eslint-plugin-my-rule", "main": "./dist/index.js", "files": [ "dist/**" ], ...
接着在src资料夹内加入index.tsmodule.exports = { rules: { // our rules will go here },};
接着新增一个myRule.tsimport { Rule } from "eslint";export const myRule: Rule.RuleModule { create(context){ return {}; }}
接着就可以在index.ts引入我们的Ruleimport { myRule } from './myRule';module.exports = { rules: { 'my-rule': myRule, },};
接着在package.json中加入scripts"scripts": { "build": "tsup src/index.ts --no-splitting --minify"},
接下来当我们开发完我们只需要执行npm run build
就可以在dist生成我们要的程式码了
接着你只需要在本地安装他或是用npm publish把他发布出去,就可以使用了
// 上传npm i eslint-plugin-my-rule// 本地npm i ./path-to-your-plugin/eslint-plugin-my-rule
最后最后,在.eslintrc.js加上Rule{ "plugins": ["my-rule"], //package name为eslint-plugin-my-rule这边只需要写my-rule "rules": { "my-rule/my-rule": "warn" // my-rule/index.ts内的rule name } ...
在写Rule时很重要的东西是context这个物件,也就是当我们检查出问题时,我们要如何去显示错误,跟错误的行数列数等等
在Eslint的官网有详细教学,可以去看看
这边我们只介绍最常用的context.report,格式如下
context.report({ message: "Error is Found!", loc: { start: { line: -1, column: -1}, end: { line: -1, column: -1}, }})
message是你会在Eslint检查上看到的message,start跟end就是你可以指定错误发生的行列数
最后如果想看更详细的,可以参考官网,有非常详细的教学
参考资料:
https://dev.to/bwca/create-a-custom-eslint-rule-with-typescript-4j3dhttps://www.darraghoriordan.com/2021/11/06/how-to-write-an-eslint-plugin-typescripthttps://eslint.org/docs/latest/extend/custom-rule-tutorial关于我:
https://www.linkedin.com/in/zhi-ping-lin/patrick41513@gmail.com