ESLint+Prettier+editorconfig

本文介绍了如何通过EditorConfig保持代码风格一致性,Prettier进行自动格式化,以及ESLint进行代码质量检查。了解如何安装配置它们,确保团队编码规范统一。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

editorconfig

官网是这么介绍EditorConfig的,“EditorConfig帮助开发人员在不同的编辑器和IDE之间定义和维护一致的编码样式.通俗一点说就是保证每个开发者的编码风格一致

首先安装EditorConfig

在代码根目录创建.editorconfig文件

# http://editorconfig.org

root = true

[*] # 表示所有文件适用
charset = utf-8 # 设置文件字符集为 utf-8
indent_style = space # 缩进风格(tab | space)
indent_size = 2 # 缩进大小
end_of_line = lf # 控制换行类型(lf | cr | crlf)
trim_trailing_whitespace = true # 去除行首的任意空白字符
insert_final_newline = true # 始终在文件末尾插入一个新行

[*.md] # 表示仅 md 文件适用以下规则
max_line_length = off
trim_trailing_whitespace = false

 此时要测试editorconfig是否生效,改变缩进大小为8,然后去文件中按tab键,如果缩进是8那说明editorconfig配置成功。更多配置请移步至官网

Prettier

Prettier 是一款强大的代码格式化工具,支持 JavaScript、TypeScript、CSS、SCSS、Less、JSX、Angular、Vue、GraphQL、JSON、Markdown 等语言,基本上前端能用到的文件格式它都可以搞定,是当下最流行的代码格式化工具

1、安装prettier插件

2、项目中安装prettier

 yarn add prettier

或者

npm install prettier -D

3、配置.prettierrc文件

  • useTabs:使用tab缩进还是空格缩进,选择false;

  • tabWidth:tab是空格的情况下,是几个空格,选择2个;

  • printWidth:当行字符的长度,推荐80,也有人喜欢100或者120;

  • singleQuote:使用单引号还是双引号,选择true,使用单引号;

  • trailingComma:在多行输入的尾逗号是否添加,设置为 none

  • semi:语句末尾是否要加分号,默认值true,选择false表示不加;

{
  "useTabs": false,
  "tabWidth": 2,
  "printWidth": 80,
  "singleQuote": true,
  "trailingComma": "none",
  "semi": false
}

4、创建.prettierignore忽略文件

/dist/*
.local
.output.js
/node_modules/**

**/*.svg
**/*.sh

/public/*

5、脚本

创建脚本,运行脚本会对所有的非prettier忽略文件做格式化

至此,你之后保存文件的时候就会按照prettier文件定义好的格式去进行格式化 

ESLint

我们使用 Eslint 做代码 lint,那么为什么还要使用 .editorconfig 呢?

eslint确实有不少editorconfig的属性,但是有些属性没有比如insert_final_newline。eslint更偏向于语法提示,而 .editorconfig 更偏向于代码风格,如缩进等

1、安装eslint插件

2、安装依赖

npm i eslint

或者

yarn add eslint 

3、配置.eslintrc文件

module.exports = {
  root: true,
  env: {
    node: true
  },
  extends: [
    'plugin:vue/vue3-essential',
    'eslint:recommended',
    '@vue/typescript/recommended',
    'plugin:prettier/recommended'
  ],
  parserOptions: {
    ecmaVersion: 2020
  },
  rules: {
    'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off'
  }
}

这里要特别注意,如果是脚手架生成的eslint+prettier的话,这个文件不需要改 

 4、安装eslint和prettier冲突插件

npm i eslint-plugin-prettier eslint-config-prettier -D

 5、在eslintrc文件中配置extends:'plugin:prettier/recommended'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值