在 JavaScript 的早期,開發者缺乏統一的規範,程式碼容易因個人習慣而變得混亂。
今天,ESLint 已經成為 JavaScript/TypeScript 專案裡最常見的程式碼檢查工具。
和昨天的 Prettier 不同,ESLint 專注於 程式邏輯與最佳實踐。
var
、避免 any
、規定函式宣告風格。👉 簡單來說:
這邊也建議在 VSCode 裡安裝 ESLint 套件:
在專案裡安裝 ESLint 以及相關套件:
npm install eslint @eslint/js eslint-config-prettier eslint-plugin-prettier @typescript-eslint/parser @typescript-eslint/eslint-plugin --save-dev
在專案根目錄新增 eslint.config.js
:
const js = require("@eslint/js");
const globals = require("globals");
const prettier = require("eslint-config-prettier");
const tsParser = require("@typescript-eslint/parser");
const tsPlugin = require("@typescript-eslint/eslint-plugin");
module.exports = [
{
files: ["**/*.ts"], // 檢查 .ts 檔案
languageOptions: {
parser: tsParser, // 用 TypeScript 的解析器
sourceType: "module", // 支援 ES 模組
globals: {
...globals.node, // Node.js 的全域變數(像 process)
},
},
plugins: {
"@typescript-eslint": tsPlugin, // TypeScript 專屬插件
prettier: require("eslint-plugin-prettier"), // Prettier 插件
},
rules: {
...js.configs.recommended.rules, // ESLint 基本規則
...tsPlugin.configs.recommended.rules, // TypeScript 推薦規則
...prettier.rules, // 正確使用 prettier 配置
"prettier/prettier": "error", // Prettier 格式錯誤會顯示
semi: ["error", "always"], // 行尾一定要有分號
quotes: ["error", "double"], // 用雙引號
"no-var": "error", // 不准用 var
"@typescript-eslint/no-unused-vars": ["error"], // 不准有沒用到的變數
"@typescript-eslint/no-explicit-any": "error", // 禁止使用 any 類型
// 改用 TypeScript 版本的 func-style
"func-style": ["error", "declaration", { allowArrowFunctions: true }],
// 禁止一般函式表達式
"no-restricted-syntax": [
"error",
{
selector: "FunctionExpression",
message: "請使用函式宣告式或箭頭函式,避免使用一般函式表達式 😎",
},
],
},
},
];
在 package.json
裡加上 script:
"scripts": {
"lint": "eslint \"src/**/*.ts\"",
"lint:fix": "eslint \"src/**/*.ts\" --fix"
}
npm run lint
:檢查程式碼規則npm run lint:fix
:自動修復能修的錯誤在 /src
下新增 testLint.ts
:
import express from "express";
const app = express();
// 違反 1: sayHello 宣告但未使用
function sayHello(name: any) {
// 違反 2: 用 any 型別(TypeScript 規則)
var greeting = "Hello " + name; // 違反 3: 用 var 宣告
let unusedVar = 42; // 違反 4: 未使用的變數
console.log(greeting);
}
// 違反 5:請使用函式宣告式或箭頭函式,避免使用一般函式表達式
const a = function (name: string) {
console.log(name);
};
a("Peter");
app.get("/test", (req, res) => {
res.send("Test route");
});
app.listen(3000, () => {
console.log("Server running on port 3000");
});
執行:
npm run lint
你會看到 ESLint 把所有違規都列出來,幫助你更快找到問題。
commit : setup ESLint
👉 明天 (Day14) 我們則會來介紹 Zod 驗證 (API 驗證守護神),期待期待 💪