ESLint 공식문서의 Custom Rules 페이지의 일부 내용을 정리해보았다.
규칙을 적용할 Node AST 타입 확인하기
// basic format
module.exports = {
meta: {
type: "suggestion",
docs: {
description: "Description of the rule",
},
fixable: "code",
schema: [] // no options
},
create: function(context) {
return {
// callback functions
};
}
};
:exit
을 붙인 node type이나 selector일 경우 해당하는 노드를 위에서 아래로 탐색하는 visitor 함수 호출context 객체는 create 함수의 유일한 인자이다.
context 객체의 파라미터 (deprecated 제외)
context 객체의 method (deprecated 제외)
report 함수는 아래 속성을 포함하는 하나의 객체를 인자로 받는다. node 또는 loc 둘 중에 하나는 반드시 지정되어야 한다.
data에 설정된 변수(placeholder)를 사용하여 message를 작성할 수 있다. message의 string 안에 {{변수}} 형태로 사용해주면 된다.
context.report({
node: node,
message: "Unexpected identifier: {{ identifier }}",
data: {
identifier: node.name
}
});
meta에 설정된 messages를 사용하여 message를 작성할 수 있다. messageId에 해당하는 message를 지정해주면 된다.
module.exports = {
meta: {
messages: {
avoidName: "Avoid using variables named '{{ name }}'"
}
},
create(context) {
return {
Identifier(node) {
if (node.name === "foo") {
context.report({
node,
messageId: "avoidName",
data: {
name: "foo",
}
});
}
}
};
}
};
잘못 작성된 코드를 자동으로 수정하는 기능이다.
반드시 meta.fixable 프로퍼티가 설정되어야 fix 함수를 사용할 수 있다.
fix 함수는 fixer 객체를 인자로 받는다.
fixer 객체의 method
위 메서드들은 fixing 객체를 반환하며, fix 함수는 아래 항목들을 리턴할 수 있다.
fix(fixer) {
return fixer.insertTextAfter(node, ";");
}
*fix(fixer) {
yield fixer.replaceText(node, replacementText);
// extend range of the fix to the range of `node.parent`
yield fixer.insertTextBefore(node.parent, "");
yield fixer.insertTextAfter(node.parent, "");
}
fix가 기능을 변경할 가능성이 있거나 규칙을 수정할 다양한 방법이 있다면 fix 대신에 suggestion을 사용할 수 있다.
반드시 meta.hasSuggestions 프로퍼티가 설정되어야 suggest 옵션을 사용할 수 있다.
report 객체에 여러 개의 suggestion 객체를 포함한 배열인 suggest 옵션을 추가해준다. 각 suggestion 객체는 desc나 messageId 둘 중에 하나와 fix key를 가진다.
context.report({
node: node,
message: "Unnecessary escape character: \\{{character}}.",
data: { character },
suggest: [
{
desc: "Remove the `\\`. This maintains the current functionality.",
fix: function(fixer) {
return fixer.removeRange(range);
}
},
{
desc: "Replace the `\\` with `\\\\` to include the actual backslash character.",
fix: function(fixer) {
return fixer.insertTextBeforeRange(range, "\\");
}
}
]
});
schema 객체를 사용하여 규칙의 config option 구조를 설정할 수 있다.
// Valid configuration:
// "yoda": "warn"
// "yoda": ["error"]
// "yoda": ["error", "always"]
// "yoda": ["error", "never", { "exceptRange": true }]
// Invalid configuration:
// "yoda": ["warn", "never", { "exceptRange": true }, 5]
// "yoda": ["error", { "exceptRange": true }, "never"]
module.exports = {
meta: {
schema: [
{
enum: ["always", "never"]
},
{
type: "object",
properties: {
exceptRange: { type: "boolean" }
hello: {type: "string"}
},
required: ["exceptRange"],
additionalProperties: false
}
]
}
};