eslint 数组和对象非空判断整理
1 安装vscode的eslint
2 npx eslint --init 初始化eslint
3 配置文件
eslint.config.mjs
import globals from "globals";
import pluginJs from "@eslint/js";
import tseslint from "typescript-eslint";
import pluginVue from "eslint-plugin-vue";
import noNullCheck from "./no-null-check.js"; // 引入自定义规则
export default [
{files: ["**/*.{js,mjs,cjs,ts,vue}"]},
{languageOptions: { globals: globals.browser }},
...pluginVue.configs["flat/essential"],
{files: ["**/*.vue"], languageOptions: {parserOptions: {parser: tseslint.parser}}},
{
plugins: {
"example": {
rules: { "no-null-check": noNullCheck }
}
},
rules: {
"example/no-null-check": "warn", // 注册自定义规则
},
},
];
no-null-check.js
module.exports = {
meta: {
type: "problem",
docs: {
description: "require non-empty initialization for arrays and objects, and check usage in lifecycle methods",
category: "Best Practices",
recommended: false,
},
schema: [],
},
create: function (context) {
const dataProperties = {};
return {
VariableDeclaration(node) {
node.declarations.forEach(declaration => {
const { init } = declaration;
if (init) {
if (
(init.type === 'ArrayExpression' && init.elements.length === 0) ||
(init.type === 'ObjectExpression' && init.properties.length === 0)
) {
context.report({
node: declaration,
message: 'Initialization should not be empty for arrays or objects.',
});
}
}
});
},
'Property[key.name="data"]'(node) {
if (node.value.type === 'FunctionExpression') {
const returnStatement = node.value.body.body.find(
stmt => stmt.type === 'ReturnStatement'
);
if (returnStatement && returnStatement.argument.type === 'ObjectExpression') {
returnStatement.argument.properties.forEach(prop => {
dataProperties[prop.key.name] = prop.value;
if (
(prop.value.type === 'ArrayExpression' && prop.value.elements.length === 0) ||
(prop.value.type === 'ObjectExpression' && prop.value.properties.length === 0)
) {
context.report({
node: prop,
message: '记得非空判断',
});
}
});
}
}
},
MemberExpression(node) {
if (node.object.name === 'this' && dataProperties[node.property.name]) {
const prop = dataProperties[node.property.name];
if (
(prop.type === 'ArrayExpression' && prop.elements.length === 0) ||
(prop.type === 'ObjectExpression' && prop.properties.length === 0)
) {
context.report({
node,
message: 'Data property should be checked for non-emptiness before usage.',
});
}
}
},
};
},
};