React Monorepo中ESLint扩展配置:如何避免重复编写import/order规则
如何在ESLint继承配置时避免重复编写规则?
在ReactJS Monorepo环境中配置web和UI包的ESLint时,web包的配置需要继承base配置,但遇到了一个问题:想给import/order规则新增pathGroups属性,却不得不重写整个规则配置,导致代码重复。
当前配置文件
./base.json(UI包专用)
{ "extends": ["next", "prettier"], "plugins": ["prettier", "@typescript-eslint", "unused-imports"], "rules": { "no-unused-vars": "off", "no-duplicate-imports": "off", "no-console": "warn", "no-return-await": "warn", "no-useless-return": "warn", "no-var": "warn", "react-hooks/exhaustive-deps": "off", "import/order": [ "warn", { "groups": ["type", "builtin", "external", "internal", "parent", "sibling", "index", "object"], "newlines-between": "always" } ], } }
./web.json(web包专用,继承base)
{ "extends": ["./base.json", "next/core-web-vitals"], "rules": { "@next/next/no-img-element": "off", "import/order": [ "warn", { "groups": ["type", "builtin", "external", "internal", "parent", "sibling", "index", "object"], "pathGroups": [ { "pattern": "@/custom/**", "group": "internal" }, ], "newlines-between": "always", } ], } }
解决方案:改用JS格式的ESLint配置文件
ESLint的JSON配置不支持对象合并逻辑,只能完全覆盖规则。换成JS格式的配置文件后,可以利用JavaScript的对象解构与扩展运算符,实现规则配置的部分扩展,避免重复代码。
步骤1:将base.json改为base.js
module.exports = { extends: ["next", "prettier"], plugins: ["prettier", "@typescript-eslint", "unused-imports"], rules: { "no-unused-vars": "off", "no-duplicate-imports": "off", "no-console": "warn", "no-return-await": "warn", "no-useless-return": "warn", "no-var": "warn", "react-hooks/exhaustive-deps": "off", "import/order": [ "warn", { groups: ["type", "builtin", "external", "internal", "parent", "sibling", "index", "object"], newlines-between: "always" } ] } };
步骤2:将web.json改为web.js,导入并扩展base配置
const baseConfig = require('./base.js'); module.exports = { // 继承base的基础配置 ...baseConfig, // 扩展extends数组,添加next/core-web-vitals extends: [...baseConfig.extends, 'next/core-web-vitals'], rules: { // 继承base所有规则 ...baseConfig.rules, // 新增web专属规则 "@next/next/no-img-element": "off", // 扩展import/order规则,仅新增pathGroups "import/order": [ // 保留base中规则的级别(warn) baseConfig.rules['import/order'][0], { // 继承base中import/order的所有配置项 ...baseConfig.rules['import/order'][1], // 合并pathGroups:如果base已有则保留,新增自定义规则 pathGroups: [ ...(baseConfig.rules['import/order'][1].pathGroups || []), { pattern: "@/custom/**", group: "internal" } ] } ] } };
说明
这种方式的核心是利用JS的语法特性,对base配置中的规则进行部分扩展而非完全覆盖。后续如果base中的import/order规则有调整(比如修改groups或newlines-between),web配置会自动继承这些变化,无需手动同步重复代码。
内容的提问来源于stack exchange,提问作者Epple
相关产品推荐
相关产品推荐

