You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Prettier与ESLint拆分TypeScript/JavaScript长导入语句

实现长导入语句拆分为多独立import的配置方案

要实现将超长导入拆分为多个独立import语句的需求,需要同时调整Prettier和ESLint的配置,具体步骤如下:

1. 调整Prettier配置

首先修改你的.prettierrc,添加mergeImports: false,防止Prettier将拆分后的同路径import重新合并:

{
  "singleQuote": true,
  "trailingComma": "all",
  "printWidth": 120,
  "mergeImports": false
}

2. 配置ESLint规则

先安装eslint-plugin-import(如果尚未安装):

npm install eslint-plugin-import --save-dev

然后更新.eslintrc.json,启用import/max-len规则,设置与Prettier一致的长度阈值并开启自动修复:

{
  "extends": ["next/core-web-vitals", "next/typescript", "eslint:recommended", "plugin:import/recommended", "plugin:import/typescript"],
  "rules": {
    "@typescript-eslint/no-explicit-any": "warn",
    "import/no-anonymous-default-export": "off",
    "import/max-len": [
      "error",
      {
        "code": 120, // 与Prettier的printWidth保持一致
        "ignoreComments": true,
        "ignoreUrls": true
      }
    ],
    "import/no-duplicates": "error" // 避免出现重复导入,建议开启
  }
}

如果需要按导入成员数量拆分而非字符长度,可以替换为import/max-dependencies规则,示例配置:

"import/max-dependencies": ["error", {"max": 3}]

3. 配置VSCode自动格式化

在VSCode的settings.json中添加以下配置,确保保存时自动执行ESLint修复和Prettier格式化:

{
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "prettier.requireConfig": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode"
}

内容的提问来源于stack exchange,提问作者Islam Y-

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 19:25:06