将 ESLint 和 Prettier 添加到 Nuxt 3 ✨ (2024)
🎉 更新(2024 年 4 月):本教程现在使用该@nuxt/eslint
模块。
介绍
在本文中,我们将介绍 ESLint 和 Prettier,用于在 Nuxt 3 项目中自动进行代码样式格式化。
-
ESLint是一个 linter,它通过标准和模式帮助加强代码质量,例如标记未使用的变量、不允许全局变量以及要求 Error 对象作为 Promise 拒绝的原因。
-
Prettier是一种格式化程序,有助于整理文档,例如最大行长度、混合空格和制表符、关键字间距和逗号样式。
通过结合使用这些工具,我们可以将更多的开发时间花在实际代码上,而不是挑剔文件的缩进、大小写和括号位置。
安装
套餐
安装以下依赖项:
# ESLint
yarn add --dev @nuxt/eslint eslint typescript
# Prettier
yarn add --dev eslint-plugin-prettier eslint-config-prettier prettier
配置
将模块添加@nuxt/eslint
到您的 Nuxt 配置中:
// nuxt.config.ts
export default defineNuxtConfig({
devtools: { enabled: true },
modules: [
// ...
'@nuxt/eslint',
// ...
],
})
运行yarn dev
以生成初始 ESLint 配置文件(eslint.config.mjs
),它将如下所示:
// eslint.config.mjs
import withNuxt from './.nuxt/eslint.config.mjs'
export default withNuxt()
如果您已经有一个想要使用的 ESLint 扁平配置文件,可以将其作为参数传递给
withNuxt()
。
您可以在这里探索更多配置选项:https://eslint.nuxt.com/packages/module
脚本
将以下脚本添加到您的package.json
文件中:
// package.json
{
"scripts": {
// ...
"lint": "yarn lint:eslint && yarn lint:prettier",
"lint:eslint": "eslint .",
"lint:prettier": "prettier . --check",
"lintfix": "eslint . --fix && prettier --write --list-different ."
// ...
}
}
用法
要检查错误,请使用yarn lint
。这不会影响任何更改,并且可能在代码审查或 CI 管道中很有用。
$ yarn lint
>>> yarn run v1.22.5
>>> $ yarn lint:eslint && yarn lint:prettier
>>> $ eslint .
>>> $ prettier . --check
>>> Checking formatting...
>>> [warn] app.vue
>>> [warn] Code style issues found in the above file. Run Prettier to fix.
>>> error Command failed with exit code 1.
>>> info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
>>> error Command failed with exit code 1.
>>> info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
要修复错误,请使用yarn lintfix
。这将保存所有格式更改。
$ yarn lintfix
>>> yarn run v1.22.5
>>> $ prettier --write --list-different . && eslint . --fix
>>> app.vue
>>> Done in 2.59s.
使用后yarn lintfix
,调用yarn lint
应该会成功。
$ yarn lint
>>> yarn run v1.22.5
>>> $ yarn lint:eslint && yarn lint:prettier
>>> $ eslint .
>>> $ prettier . --check
>>> Checking formatting...
>>> All matched files use Prettier code style!
>>> Done in 3.07s.
全部完成!
希望你现在可以避免那些吹毛求疵的争论了
嘿,大家!感谢阅读。希望你们喜欢这篇文章。
关注我的最新动态:
- 网站:https://lloyd.cx/
- 推特: https: //twitter.com/lloydtao/
- GitHub:https://github.com/lloydtao/
- 领英:https://www.linkedin.com/in/lloydtao/