一、Eslint
eslint是做 js、ts 的代码格式化的,但是扩展性很强,包括变量是否使用,是否要console.log。
1、安装
先安装 npm 包,再安装vscode插件。
yarn add eslint -D
2、配置
执行 eslint 命令初始化:
npx eslint --init
编辑根目录创建的 .eslintrc.js 文件:
module.exports = {env:{browser:true,es2021:true,node:true},extends: ["prettier","plugin:@typescript-eslint/recommended","plugin:eslint-comments/recommended","prettier/react","prettier/@typescript-eslint"],//rules部分, 0是忽略,1是警告,2是报错rules:{quotes:0,semi:0,"react-hooks/rules-of-hooks": "error","react-hooks/exhaustive-deps": "warn",// "no-multi-spaces": 1, // 不能用多余的空格// "react/jsx-tag-spacing": 1, // 总是在自动关闭的标签前加一个空格,正常情况下也不需要换行// "jsx-quotes": 1, //在 JSX 属性中使用一致的单引号或双引号// "react/jsx-closing-bracket-location": 1, // 遵循JSX语法缩进/格式// "react/jsx-boolean-value": 1, // 如果属性值为 true, 可以直接省略// "react/no-string-refs": 1, // 总是在Refs里使用回调函数// "react/self-closing-comp": 1, // 对于没有子元素的标签来说总是自己关闭标签// "react/sort-comp": 1, // 按照具体规范的React.createClass 的生命周期函数书写代码// "react/jsx-pascal-case": 1 // React模块名使用帕斯卡命名,实例使用骆驼式命名},}
3、规则
配置文件 rules 规则中的值 0,1,2 分别代表:忽略、警告、报错。
4、格式修复
eslint index.js --fix
二、Prettier
prettier是做所有代码的格式化,并且只专注于格式化,范围更广。
vscode的插件可以单独配置,单独起作用。但是如果项目根目录中有.eslintrc.js和.prettierrc.js文件,则以.eslintrc.js和.prettierrc.js的配置为标准,执行它们的配置。
1、安装
先安装 npm 包,再安装vscode插件。
yarn add prettier -D
2、配置
编辑根目录创建的 .prettierrc.js 文件:
module.exports = {singleQuote: true, // 单引号trailingComma: "all",printWidth: 100,proseWrap: "never",semi: false, // 不需分号// "tabWidth": 4, // 水平缩进的空格数,默认为 2overrides: [{files: ".prettierrc",options: {parser: "json"}},{files: "document.ejs",options: {parser: "html"}}]};
