單一儲存庫中的 ESLint

安裝 ESLint

建議為簡便起見,保留單一版本的 ESLint。因此,我們建議在單一儲存庫的根目錄中將 ESLint 安裝為 devDependency,或使用類似 syncpack(在新分頁中開啟) 的工具,在工作區中維護相同的版本。

共用設定檔

在工作區中共用 ESLint 設定檔有助於提升生產力,讓所有工作區更一致。

想像一下類似這樣的單一儲存庫

apps
├─ docs
│  ├─ package.json
│  └─ .eslintrc.js
└─ web
   ├─ package.json
   └─ .eslintrc.js
packages
└─ eslint-config-custom
   ├─ next.js
   ├─ library.js
   └─ package.json

我們有一個名為 eslint-config-custom 的套件,以及兩個應用程式,每個應用程式都有自己的 .eslintrc.js

我們的 eslint-config-custom 套件

我們的 eslint-config-custom 檔案包含兩個檔案,next.jslibrary.js。這兩個是不同的 ESLint 設定檔,我們可以根據需要在不同的工作區中使用它們。

讓我們探討 next.js 的 linter 設定

const { resolve } = require("node:path");
 
const project = resolve(process.cwd(), "tsconfig.json");
 
/*
 * This is a custom ESLint configuration for use with
 * Next.js apps.
 *
 * This config extends the Vercel Engineering Style Guide.
 * For more information, see https://github.com/vercel/style-guide
 *
 */
 
module.exports = {
  extends: [
    "@vercel/style-guide/eslint/node",
    "@vercel/style-guide/eslint/typescript",
    "@vercel/style-guide/eslint/browser",
    "@vercel/style-guide/eslint/react",
    "@vercel/style-guide/eslint/next",
    // turborepo custom eslint configuration configures the following rules:
    //  - https://github.com/vercel/turbo/blob/main/packages/eslint-plugin-turbo/docs/rules/no-undeclared-env-vars.md
    "eslint-config-turbo",
  ].map(require.resolve),
  parserOptions: {
    project,
  },
  globals: {
    React: true,
    JSX: true,
  },
  settings: {
    "import/resolver": {
      typescript: {
        project,
      },
    },
  },
  ignorePatterns: ["node_modules/", "dist/"],
  // add rules configurations here
  rules: {
    "import/no-default-export": "off",
  },
};

這是一個典型的 ESLint 設定,擴充了 Vercel styleguide (在新分頁中開啟),沒有什麼特別的。

這個 package.json 如下所示

{
  "name": "eslint-config-custom",
  "license": "MIT",
  "version": "0.0.0",
  "private": true,
  "devDependencies": {
    "@vercel/style-guide": "^4.0.2",
    "eslint-config-turbo": "^1.10.12"
  }
}
 

請注意,ESLint 的相依性都列在這裡。這很有用,表示我們不需要在匯入 eslint-config-custom 的應用程式中重新指定相依性。

如何使用 eslint-config-custom 套件

在我們的 web 應用程式中,我們首先需要將 eslint-config-custom 加入為相依性。

{
  "dependencies": {
    "eslint-config-custom": "*"
  }
}

然後我們可以像這樣匯入設定

module.exports = {
  root: true,
  extends: ["custom/next"],
};

custom/next 加入我們的 extends 陣列中,我們告訴 ESLint 尋找一個名為 eslint-config-custom 的套件,並參考檔案 next.js

您可以透過設定套件的進入點來避免指定檔案。例如,在 package.json 中設定 main: 'next.js',可以在 .eslintrc.js 中簡單地載入為 extends: ["custom"]

摘要

當您使用 npx create-turbo@latest 建立新的單一儲存庫時,此設定會預設出貨。您也可以查看 我們的基本範例(在新分頁中開啟) 以查看工作版本。

設定 lint 任務

我們建議遵循 基礎 部分的設定,並進行一項變更。

每個 package.json 腳本應如下所示

{
  "scripts": {
    "lint": "eslint ."
  }
}