問題描述
在使用?pnpm lint
?運行 ESLint 時,出現以下錯誤:
Oops! Something went wrong! :(
ESLint: 9.31.0
ReferenceError: prettier is not defined
該錯誤導致 ESLint 無法正確執行代碼格式檢查,但?不會影響項目的實際運行(如?pnpm dev
?或?pnpm build
)。
錯誤原因
eslint-plugin-prettier
?未正確導入在?
eslint.config.js
?中使用了?prettier/prettier
?規則,但沒有正確引入?eslint-plugin-prettier
。
ESLint v9+ 的 Flat Config 格式兼容性問題
舊版 ESLint 的配置方式(如?
.eslintrc.js
)與新版?eslint.config.js
?不兼容。
解決方案
方法 1:修復?eslint.config.js
(推薦)
1. 安裝必要依賴
pnpm add -D eslint-plugin-prettier prettier
2. 修改?eslint.config.js
import { defineConfig } from "eslint/config";
import globals from "globals";
import js from "@eslint/js";
import pluginVue from "eslint-plugin-vue";
import prettierPlugin from "eslint-plugin-prettier"; // 正確導入 Prettier 插件export default defineConfig([{files: ["**/*.{js,mjs,jsx,vue}"],ignores: ["**/dist/**", "**/dist-ssr/**", "**/coverage/**"],},{languageOptions: {globals: {...globals.browser,},},},js.configs.recommended,...pluginVue.configs["flat/essential"],{plugins: {prettier: prettierPlugin, // 注冊 Prettier 插件},rules: {"prettier/prettier": ["warn",{singleQuote: true,semi: false,printWidth: 60,trailingComma: "none",endOfLine: "auto",},],"vue/multi-word-component-names": ["warn",{ ignores: ["index"] },],"vue/no-setup-props-destructure": "off","no-undef": "error",},},
]);
3. 重新運行 ESLint
pnpm lint
方法 2:降級 ESLint(兼容舊配置)
如果不想使用 ESLint v9+ 的 Flat Config,可以降級到 ESLint v8:
pnpm add eslint@8.56.0 -D
然后改用?.eslintrc.js
?配置(舊版格式):
module.exports = {extends: ["eslint:recommended","plugin:vue/essential","plugin:prettier/recommended", // 使用 Prettier 推薦配置],rules: {"prettier/prettier": ["warn",{singleQuote: true,semi: false,printWidth: 60,trailingComma: "none",endOfLine: "auto",},],"vue/multi-word-component-names": ["warn",{ ignores: ["index"] },],"vue/no-setup-props-destructure": "off","no-undef": "error",},
};