[英]How to analyze JS Literals/Identifiers using ESLint Custom Rules
我會用一個例子來解釋這個場景。
假設我有以下 JS 代碼:
$.ajax({
url: '/Department/GetAllUsers',
type: "POST",
data: data,
success: function (result) {
//Some Code
},
error: function () {
//Some Code
}
});
我想限制對控制器的那個動作的調用。 所以我為此編寫了以下自定義 ES Lint 規則:
module.exports = {
meta: {
type: "problem",
docs: {
description: "Prohibited Method",
category: "Method",
recommended: true,
url: ""
},
messages: {
messageDefault: "This method is Prohibited to use"
},
fixable: "code",
schema: [] // no options
},
create: function (context) {
return {
Literal(node) {
var literalValue = node.value.toString();
var cont = literalValue.split("/").filter(x => x.length > 1);
{
if (cont[0] === 'Department' && cont[1] === 'GetAllUsers') {
context.report({
node: node,
messageId: "messageDefault",
});
}
}
}
};
}
};
所以在這里我限制使用'Department/GetAllUsers' ,這很好用。 當我拆分字符串或將字符串分配給變量時會出現問題。 例如
var controller = "Department";
var action = "GetAllUsers";
$.ajax({
url: "/" + controller + "/" + action,
//or '/Department/' + 'GetAllUsers'
type: "POST",
data: data,
success: function (result) {
//Some Code
},
error: function () {
//Some Code
}
});
這里的限制不起作用,有沒有辦法解決 url 中的變量值? 這甚至可以使用 ESLint 嗎?
簡而言之,我想要一些類似 context.SemanticModel.GetSymbolInfo(node) 的東西,它在 Roslyn 中用於 C# 代碼分析。
謝謝
您可以使用 ESLint 的范圍管理器https://eslint.org/docs/developer-guide/scope-manager-interface
ESLint 自己的代碼庫中有很多使用范圍管理器的例子: https : //github.com/eslint/eslint/search? q = getScope
使用此 API,您可以跟蹤變量引用並檢查其分配。
請注意,這有一些限制。 例如,您將無法跨模塊邊界或函數邊界跟蹤值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.