给nuxt3添加 ESLint 和 Prettier
前言#
在这篇文章中,我们将介绍ESLint和Prettier,用于在Nuxt 3项目中自动设置代码样式格式。
配置自动设置代码样式有这些好处:
- 一致性:自动执行某种风格。特别是在代码审查中避免吹毛求疵的论点。
- 节省时间:无需手动格式化代码。
- 代码质量:捕捉代码中的潜在问题,例如语法错误和编码风格冲突。
正文#
安装依赖#
# ESLint
yarn add --dev eslint
# Prettier
yarn add --dev prettier eslint-config-prettier eslint-plugin-prettier
# TypeScript support
yarn add --dev typescript @typescript-eslint/parser @nuxtjs/eslint-config-typescript
配置#
将以下规则添加到ESLint配置(.eslintrc.cjs):
// .eslintrc.cjs
module.exports = {
root: true,
env: {
browser: true,
node: true,
},
parser: 'vue-eslint-parser',
parserOptions: {
parser: '@typescript-eslint/parser',
},
extends: ['@nuxtjs/eslint-config-typescript', 'plugin:prettier/recommended'],
plugins: [],
rules: {},
}
将以下规则添加到Prettier配置(.prettierrc.cjs):
module.exports = {
/*打印宽度,超过后,会将属性换行*/
printWidth: 120,
/*禁止使用尾随逗号,对象和数组最后一个逗号去掉*/
trailingComma: "none",
/*在对象字面量中的括号之间添加空格*/
bracketSpacing: true,
/*使用单引号而不是双引号来定义字符串*/
singleQuote: true,
/*当箭头函数只有一个参数时,省略参数前后的括号*/
arrowParens: "avoid",
/*script和style标签中间的内容缩进*/
vueIndentScriptAndStyle: true,
// 将>多行 HTML(HTML、JSX、Vue、Angular)元素放在最后一行的末尾,而不是单独放在下一行(不适用于自闭合元素
bracketSameLine:false
};
添加脚步命令#
// package.json
{
// ...
"scripts": {
// ...
"lint:js": "eslint --ext \".ts,.vue\" --ignore-path .gitignore .",
"lint:prettier": "prettier --check .",
"lint": "yarn lint:js && yarn lint:prettier",
"lintfix": "prettier --write --list-different . && yarn lint:js --fix"
// ...
}
// ...
}
补充#
这里强烈建议给项目增加一个 .editorconfig
文件,可以约束代码编辑器的基本规则
// .editorconfig 文件
# http://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 4
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
insert_final_newline = false
trim_trailing_whitespace = false
参考:https://dev.to/tao/adding-eslint-and-prettier-to-nuxt-3-2023-5bg
以和为贵!让 ESlint、Prettier 和 EditorConfig 互不冲突
作者:水车
出处:https://www.cnblogs.com/shuiche/p/17964098
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
推荐一个激活软件下载站:mac.shuiche.cc
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
2020-01-14 yum离线安装rpm包
2018-01-14 centos6 防火墙iptables操作整理
2017-01-14 我的CSS命名规则