eslint: plugins

简介

每个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"
    }
}
Testing

查看

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值