Node 中用 ESLint 驗證代碼

前言

ESLint 咱們通常用在項目工程裏,用來監督咱們的代碼格式、風格等;javascript

另外也能用來檢驗一段代碼字符串是否是符合規則。css

//能夠對 code 這個字符串進行驗證,例如咱們不容許使用 location.href
let code = 'location.href="zhengxiaoer.cn";'; 
複製代碼

使用場景:當這段代碼串是用戶提供的時候時,咱們能夠靜態的進行一些驗證(固然,因爲 JavaScript 太靈活,這樣的驗證徹底限制不了用戶,能繞過的方法太多)。java

怎麼用 官方文檔

一、先安裝 ESLintnpm install -s eslintyarn add eslintnode

二、代碼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 插件 ,能夠結合本身的須要,發揮想象力。官方介紹數據結構

相關文章
相關標籤/搜索