分享設定
若要分享您的 ESLint 設定,請建立一個可分享的設定。您可以將您的可分享設定發佈到 npm,讓其他人可以下載並在他們的 ESLint 專案中使用。
此頁面說明如何建立和發佈可分享的設定。
建立可分享的設定
可分享的設定只是匯出設定物件或陣列的 npm 套件。首先,像平常一樣建立一個 Node.js 模組。
雖然您可以隨意命名套件,但我們建議使用下列其中一種慣例,讓您的套件更容易識別
- 以
eslint-config-
開頭,例如eslint-config-myconfig
。 - 對於 npm 作用域模組,請以
@scope/eslint-config
命名或加上前綴,例如@scope/eslint-config
或@scope/eslint-config-myconfig
。
在您的模組中,從模組的 main
進入點檔案匯出可分享的設定。預設的主要進入點是 index.js
。例如
// index.js
export default [
{
languageOptions: {
globals: {
MyGlobal: true
}
},
rules: {
semi: [2, "always"]
}
}
];
因為 index.js
檔案只是 JavaScript,您可以從檔案讀取這些設定或動態產生它們。
發佈可分享的設定
一旦您的可分享設定準備就緒,您可以將其發佈到 npm 與他人分享。我們建議在 package.json
檔案中使用 eslint
和 eslintconfig
關鍵字,以便其他人可以輕鬆找到您的模組。
您應該使用 peerDependencies 欄位在 package.json
中宣告您對 ESLint 的依賴性。為了確保未來相容性的建議方法是使用「>=」範圍語法,並使用最低要求的 ESLint 版本。例如
{
"peerDependencies": {
"eslint": ">= 9"
}
}
如果您的可分享設定依賴外掛或自訂解析器,您應該在您的 package.json
中將這些套件指定為 dependencies
。
使用可分享的設定
若要使用可分享的設定,請在 eslint.config.js
檔案中匯入套件,並將其新增到匯出的陣列中,如下所示
// eslint.config.js
import myconfig from "eslint-config-myconfig";
export default [
...myconfig
];
覆寫可分享設定中的設定
您可以通過在匯入可分享設定後直接將設定新增到您的 eslint.config.js
檔案中,來覆寫可分享設定中的設定。例如
// eslint.config.js
import myconfig from "eslint-config-myconfig";
export default [
...myconfig,
// anything from here will override myconfig
{
rules: {
"no-unused-vars": "warn"
}
}
];
分享多個設定
由於可分享的設定只是 npm 套件,您可以從同一個套件匯出任意數量的設定。除了使用 package.json
中的 main
條目指定預設設定外,您還可以通過將新檔案新增到您的 npm 套件,然後從您的 eslint.config.js
檔案中參考它,來指定其他可分享的設定。
例如,您可以在您的 npm 套件的根目錄中建立一個名為 my-special-config.js
的檔案並匯出一個設定,例如
// my-special-config.js
export default {
rules: {
quotes: [2, "double"]
}
};
然後,假設您使用的是套件名稱 eslint-config-myconfig
,您可以使用以下方式存取其他設定
// eslint.config.js
import myconfig from "eslint-config-myconfig";
import mySpecialConfig from "eslint-config-myconfig/my-special-config.js";
export default [
...myconfig,
mySpecialConfig,
// anything from here will override myconfig and mySpecialConfig
{
rules: {
"no-unused-vars": "warn"
}
}
];