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

Next.js 13中Prettier/ESLint错误格式化'useClient'问题求助

解决Next.js 13 App Router中'useClient'格式化异常问题

核心排查与修复步骤

1. 消除Prettier与ESLint规则冲突

确保项目安装并配置了兼容插件,避免两者规则互斥:

  • 安装依赖:
    npm install eslint-config-prettier eslint-plugin-prettier --save-dev
    
  • 在.eslintrc中更新配置:
    {
      "extends": [
        "next/core-web-vitals",
        "prettier"
      ],
      "plugins": ["prettier"],
      "rules": {
        "prettier/prettier": "error"
      }
    }
    

2. 强制'useClient'指令单独成行

Next.js的'useClient'指令必须独占一行,可通过配置锁定格式:

  • 在.prettierrc中添加规则适配Next.js文件:
    {
      "printWidth": 80,
      "tabWidth": 2,
      "arrowParens": "always",
      "overrides": [
        {
          "files": ["*.tsx", "*.jsx"],
          "options": {
            "parser": "typescript"
          }
        }
      ]
    }
    
  • 若仍有问题,在ESLint中添加强制指令换行规则:
    {
      "rules": {
        "lines-around-directive": ["error", { "before": "always", "after": "always" }]
      }
    }
    

3. 同步EditorConfig与Prettier配置

避免编辑器层面的格式化干扰,确保.editorconfig与Prettier设置一致:

root = true

[*]
charset = utf-8
end_of_line = lf
indent_size = 2
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true

[*.md]
trim_trailing_whitespace = false

重点检查indent_size是否匹配Prettier的tabWidth,end_of_line是否统一。

4. 验证并执行格式化命令

确保package.json中的脚本命令正确调用工具:

{
  "scripts": {
    "lint": "next lint",
    "format": "prettier --write .",
    "format:check": "prettier --check ."
  }
}

先手动执行npm run format验证效果,再测试编辑器保存自动格式化。

5. 更新依赖版本

旧版本工具可能存在兼容性问题,尝试更新到最新稳定版:

npm update prettier eslint eslint-config-next eslint-config-prettier eslint-plugin-prettier

内容的提问来源于stack exchange,提问作者Thales Maia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 06:25:06