返回文章列表

在 VS Code 中設定 Next.js 13 的 ESLint 與 Prettier

跟著本指南,輕鬆為你的 Next.js 13 專案在 VS Code 中設定 ESLint 和 Prettier,讓程式碼始終整潔、風格一致。

發佈於 2023年10月24日·2 分鐘

1. 設定 Next.js 13 的 ESLint

使用 npx create next-app@latest 建立專案時,選擇加入 ESLint。

2. 加入 ESLint 設定檔

先執行:

npm install eslint-config-standard

這會在專案中安裝 standard 風格的 ESLint 設定。接著把它加入 .eslintrc.json 檔案中:

{
  "extends": ["next/core-web-vitals", "standard"]
}

3. 為 TailwindCSS 加入 ESLint 設定

執行:

npm install eslint-plugin-tailwindcss

接著把它加入 .eslintrc.json 檔案中:

{
  "extends": [
    "next/core-web-vitals",
    "standard",
    "plugin:tailwindcss/recommended"
  ]
}

4. Prettier 與 ESLint 的潛在衝突

ESLint 有時會和 Prettier 發生衝突。為了避免這種情況,你需要執行:

npm install eslint-config-prettier

這個套件會關閉所有可能與 Prettier 衝突的 ESLint 規則。安裝完成後,把 "prettier" 加入 .eslintrc.json 檔案中。

{
  "extends": [
    "next/core-web-vitals",
    "standard",
    "plugin:tailwindcss/recommended",
    "prettier"
  ]
}

5. 安裝 Prettier

繼續之前別忘了安裝 Prettier。執行:

npm install prettier

6. 設定 VSCode

指令列層面的設定都完成了,接下來把 ESLint 和 Prettier 整合進 VSCode。為此,我們需要修改 settings.json 檔案,或者為專案單獨建立一份設定,這樣還可以方便地分享給其他人。這裡我們採用後一種方式。

在 Next.js 專案的根目錄下建立一個 .vscode 資料夾,並在其中新增一個 settings.json 檔案,寫入以下程式碼:

{
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true,
    "source.addMissingImports": true
  },
  "[typescriptreact]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  }
}

這樣 ESLint 和 Prettier 就能在 VSCode 中協同運作了。每次儲存檔案時,Prettier 和 ESLint 都會自動執行。不過想真正看到效果,還剩最後一步……

7. 從擴充功能市集安裝 ESLint 和 Prettier

兩個擴充功能都裝好之後,重新啟動 Visual Studio Code。現在試著編輯並儲存一些檔案,你應該能看到 Prettier 和 ESLint 已經生效了。要驗證 Tailwind CSS 外掛是否也正常運作,可以把 flex 類別名稱放到類別清單的最後,儲存後看它是否被自動排回前面。