Nuxt3+ESlint扁平化配置

总结一下 Nuxt3 + ESlint 扁平化配置

2024/4/16

前段时间在 Nuxt3 项目中使用 ESLint 时,发现 ESLint 更新了 9.0.0 版本,使用扁平化配置,在集成过程中遇到了些许问题,特此记录一下(在网上了解到扁平化配置早在 ESLint v9.0.0 前就提出来了)。

关于 ESLint v9.0.0 迁移指南:

从 ESLint v9.0.0 开始,扁平配置文件格式将成为默认配置文件格式。ESLint v9.0.0 发布后,你可以开始使用扁平配置文件格式,无需任何额外配置。(关于扁平化配置

要将扁平配置与 ESLint v8 结合使用,请将 eslint.config.js 文件放置在项目的根目录中或将 ESLINT_USE_FLAT_CONFIG 环境变量设置为 true。

开始配置

1.创建一个 Nuxt3 项目

具体创建步骤见官方文档吧,此处略过。

2.安装 ESLint 相关依赖

npm init @eslint/config

以上命令可通过选择配置进行 ESLint 相关依赖安装:

√ How would you like to use ESLint? · problems
√ What type of modules does your project use? · esm
√ Which framework does your project use? · vue
√ Does your project use TypeScript? · typescript
√ Where does your code run? · browser, node
The config that you've selected requires the following dependencies:

eslint, globals, @eslint/js, typescript-eslint, eslint-plugin-vue
√ Would you like to install them now? · No / Yes
√ Which package manager do you want to use? · npm

于是,package.json 文件中的依赖:

"devDependencies": {
    "@eslint/js": "^9.0.0",
    "eslint": "^8.57.0",
    "eslint-plugin-vue": "^9.25.0",
    "globals": "^15.0.0",
    "typescript-eslint": "^7.7.0"
  }

此时,ESLint 还是 v8.57.0 ,也适用扁平化配置的(在使用最新版本时,也是要考虑其他插件是否有跟上,不要一味最求最新版本)

同时也生成了 esllint.config.js 文件:

import globals from "globals";
import pluginJs from "@eslint/js";
import tseslint from "typescript-eslint";
import pluginVue from "eslint-plugin-vue";


export default [
  {languageOptions: { globals: {...globals.browser, ...globals.node} }},
  pluginJs.configs.recommended,
  ...tseslint.configs.recommended,
  ...pluginVue.configs["flat/essential"],
];

3. 考虑到是 Nuxt3 项目,多加一个 @nuxt/eslint

安装及配置 @nuxt/eslint 详见官方文档吧

再说一嘴,我将默认配置关掉了(具体为什么我忘记了,TODO 记起来再补充吧):

// nuxt.config.js

modules: ["@nuxt/eslint"],
eslint: {
  config: {
    standalone: false // 关闭默认配置(默认情况下,此模块会使用推荐的规则安装 JS、TS 和 Vue 插件)
  }
}

至此,ESLint 基本配置完成啦,但是还有要修改及配置的,继续往下吧。

4.配置 eslint.config.js

以下是我的配置:

import withNuxt from "./.nuxt/eslint.config.mjs"
import globals from "globals"
import pluginJs from "@eslint/js"
import tseslint from "typescript-eslint"
import pluginVue from "eslint-plugin-vue"

export default withNuxt(
  [
    {
      languageOptions: {
        globals: { ...globals.browser, ...globals.node, ...globals.es2021 },
        ecmaVersion: "latest",
        parser: tseslint.parser
      }
    },
    pluginJs.configs.recommended,
    ...tseslint.configs.recommended,
    ...pluginVue.configs["flat/recommended"], // Vue3
    {
      rules: {
        // 写上规范代码的规则,具体规则参考 ESLint 官方文档啦
      }
    },
    { ignores: [".nuxt/"] } // 忽略校验 .nuxt/ 目录下的所有文件
  ]

)

与默认生成的配置文件相比:

  • 使用 withNuxt()
  • languageOptions.globals 多加环境: globals.es2021
  • languageOptions 多加属性: ecmaVersion: "latest", parser: tseslint.parser
  • 把 pluginVue.configs["flat/essential"] 改成了pluginVue.configs["flat/recommended"]

具体为什么会有这些变化,就不展开说啦,去百度吧

posted @ 2024-04-16 11:05  等等啦  阅读(1197)  评论(0)    收藏  举报