Chci, aby se vlastní eslint
pravidlo pomocí parser, AST.
V useEffect
funkce vyčištění, chci, aby se zabránilo používání některá klíčová slova.
import React, { useEffect } from 'react';
export const SomeReactFun = () => {
useEffect(() => {
return () => {
// `Hello` is some keyword I want to prevent in using cleanup function.
Hello.alert();
}
}, []);
}
tohle je můj vlastní parse funkce v parser, AST.
export default function (context) {
const filename = context.getFilename();
if (filename.includes(".test.ts")) return {};
return {
Identifier: (node) => {
if (node.name !== "useEffect" || node.parent.type !== "CallExpression")
return {};
const arrayExpressionBody = node.parent.arguments[0];
if (arrayExpressionBody.type !== "ArrowFunctionExpression") return {};
const arrowFunctionBody = arrayExpressionBody.body;
if (arrowFunctionBody.type !== "BlockStatement") return {};
const returnStatement = arrowFunctionBody.body.find((functionNode) => {
if (functionNode.type === "ReturnStatement") return true;
return false;
});
if (!returnStatement || returnStatement.type !== "ReturnStatement")
return {};
const returnStateArgument = returnStatement.argument;
if (returnStateArgument.type !== "ArrowFunctionExpression") return {};
const blockStatementInReturnState = returnStateArgument.body;
if (blockStatementInReturnState.type !== "BlockStatement") return {};
const isHelloUsedInClenaup = blockStatementInReturnState.body.find(
(nodeBody) => {
if (nodeBody.type !== "ExpressionStatement") return false;
console.log(nodeBody.expression);
if (
nodeBody.expression.type === "CallExpression" &&
nodeBody.expression.callee.object.name === "Hello"
) {
return false;
}
if (
nodeBody.expression.type === "Identifier" &&
nodeBody.expression.name === "Hello"
)
return false;
}
);
if (!isHelloUsedInClenaup) return {};
context.report({
node: isHelloUsedInClenaup,
message: "ERROR, do not use `Hello` in cleanup function",
data: { explanation: `${node.loc}` }
});
}
};
}
Ale tento kód nemůže zabránit, jako je tento
import React, { useEffect } from 'react';
export const SomeReactFun = () => {
useEffect(() => {
return () => {
Hello.alert(); // works!
Hello.someObject.a.alert(); // not works :)
}
}, []);
}
Jak mohu zabránit používání Hello
klíčové slovo v useEffect cleanup function
zcela?