简介
每个plugin都一个npm包。包名格式如下例(jquery相关):
- eslint-plugin-jquery
- @jquery/eslint-plugin
- @jquery/eslint-plugin-jquery
创建plugin
最简单的创建plugin的方式是用生成器工具:Yeoman generator
1. 暴露额外的rules给eslint使用
需要export一个与rule ID一一映射的key-value对象。 如下,新增rule: ‘dollar-sign’
module.export = {
rules: {
"dollar-sign": {
create: (context) => {
// rule实现
}
}
}
}
在eslin中使用如下:
{
"myplugin/dollar-sign": 2
}
2. export environments给eslint使用
environments对象的键是所提供的不同环境的名称,值是环境设置。
可配置的项: globals / parserOptions
module.exports = {
environments: {
jquery: {
globals: {
$: false
}
}
}
};
如上plugin中定义了一个jquery环境。这样在使用了这个plugin后,你可以在eslint中配置环境为:myplugin/jquery
3. 提供processor
您还可以创建插件,告诉ESLint如何处理JavaScript以外的文件。
module.exports = {
processors: {
"processor-name": {
// 参数为:文件内容和文件名
preprocess: function(text, filename) {
// here, you can strip out any non-JS content
// and split into multiple strings to lint
return [ // return an array of code blocks to lint
{ text: code1, filename: "0.js" },
{ text: code2, filename: "1.js" },
];
},
// takes a Message[][] and filename
postprocess: function(messages, filename) {
// `messages` argument contains two-dimensional array of Message objects
// where each top-level array item contains array of lint messages related
// to the text that was returned in array from preprocess() method
// you need to return a one-dimensional array of the messages you want to keep
return [].concat(...messages);
},
supportsAutofix: true // (optional, defaults to false)
}
}
};
指定processor配置文件:
plugins:
- a-plugin
overrides:
- files: "*.md"
processor: a-plugin/markdown
或者在eslint中配置:
module.exports = {
processors: {
// This processor will be applied to `*.md` files automatically.
// Also, people can use this processor as "plugin-id/.md" explicitly.
".md": {
preprocess(text, filename) { /* ... */ },
postprocess(messageLists, filename) { /* ... */ }
}
}
}
4. plugins中的configs
通过在configs键下指定配置,可以在插件中捆绑配置.
查看
5. Peer Dependency
为了明确插件需要ESLint才能正常工作,您必须在插件中声明ESLint为peerDependency包.json. 插件支持是在ESLint版本0.8.0中引入的。确保peerDependency指向ESLint 0.8.0或更高版本。
{
"peerDependencies": {
"eslint": ">=0.8.0"
}
}