ESLint 咱们通常用在项目工程里,用来监督咱们的代码格式、风格等;javascript
另外也能用来检验一段代码字符串是否是符合规则。css
//能够对 code 这个字符串进行验证,例如咱们不容许使用 location.href
let code = 'location.href="zhengxiaoer.cn";';
复制代码
使用场景:当这段代码串是用户提供的时候时,咱们能够静态的进行一些验证(固然,因为 JavaScript 太灵活,这样的验证彻底限制不了用户,能绕过的方法太多)。java
一、先安装 ESLint
, npm install -s eslint
或 yarn add eslint
node
二、代码es6
const Linter = require("eslint").Linter;
// 检查的配置
const CONFIG = {
"parser": "babel-eslint",
"env": {
"browser": true,
"es6": true
},
// rules 参考官方文档 https://eslint.bootcss.com/docs/rules/
rules: {
'no-eval': 2,//不能使用 eval
'no-with': 2,//不能使用 with
'no-delete-var': 2,//不能删除变量 delete a;
}
};
// 等待验证的代码
let code = 'eval("console.log(1+1)")';
// 初始化验证对象
let linter = new Linter();
// 开始验证
// messages 为返回的验证结果,数据结构能够查看文档 https://eslint.bootcss.com/docs/4.0.0/developer-guide/nodejs-api/
let messages = linter.verify(code, CONFIG);
复制代码
一、新建 myrule.js, 官方文档 ,一开始可能不知道怎么下手写代码,能够参考官方的验证规则源代码,进行模仿npm
假如实现对全部调用 location.href 的都不经过:api
"use strict";
module.exports = {
meta: {
},
create(context) {
// 返回须要对 AST 进行判断
//这个网址能够快速查看代码生成的 AST https://astexplorer.net
return {
// 对全部调用 location.href 的都不经过
MemberExpression: (node)=>{
let objName = node.object.name;
let propertyName = node.property.name;
if((/^location$/).test(objName) && (/^href/).test(propertyName)) {
// 返回错误数据
context.report({
node,
message: "不能使用 {{objName}}.{{propertyName}}",
data: {
objName,
propertyName
}
});
}
}
};
}
};
复制代码
二、eslint 绑定咱们的验证babel
const Linter = require("eslint").Linter;
// 检查的配置
const CONFIG = {
"parser": "babel-eslint",
"env": {
"browser": true,
"es6": true
},
// rules 参考官方文档 https://eslint.bootcss.com/docs/rules/
rules: {
'no-eval': 2,//不能使用 eval
'no-with': 2,//不能使用 with
'no-delete-var': 2,//不能删除变量 delete a;
'myrule':2, //使用咱们的规则
}
};
// 等待验证的代码
let code = 'location.href="zhengxiaoer.cn';
// 初始化验证对象
let linter = new Linter();
// 映入规则
linter.defineRules({
"myrule": require('./myrule'), // 引入js 文件
});
// 开始验证
let messages = linter.verify(code, CONFIG);
复制代码
ESLint 还能结合各种编辑器 vscode 插件 , WebStorm 插件 ,能够结合本身的须要,发挥想象力。官方介绍数据结构