如何在老项目中添加Eslint和保存自动格式化
1.在项目中安装eslint
npm i eslint typescript -D
2.在项目根目录,运行npx eslint --init
npx eslint --init
(1)按交互提示安装相关插件
(2)它会自动生成eslint的配置文件
3.设置vscode的自动保存格式化
在项目根目录下,补充配置文件:.vscodesettings.json
代码:
{ "eslint.run": "onType", "eslint.options": { "extensions": [".js", ".vue", ".jsx", ".tsx"] }, "editor.codeActionsOnSave": { "source.fixAll.eslint": true } }
在react项目中我们还需要格式化JSX代码
(1)安装vscode插件prettier-now
(2)在.vscodesettings.json文件中补充配置,代码如下:
{ "eslint.run": "onType", "eslint.options": { "extensions": [".js", ".vue", ".jsx", ".tsx"] }, "editor.codeActionsOnSave": { "source.fixAll.eslint": true }, // 编辑器设置 - 保存时做格式化 "editor.formatOnSave": true, // 编辑器设置 - 默认采用prettier-now做格式化 // 如果使用的是prettier,这的设置应该是 esbenp.prettier-vscode "editor.defaultFormatter":"remimarsal.prettier-now", // 控制缩进 "prettier.useTabs": false, // 缩进不使用tab,使用空格 "prettier.tabWidth": 2, // 缩进字节数 // 函数声明时小括号前后要加空格 // 如果你使用prettier这一项是不能做选择的,导致和eslint默认配置的冲突 // 可以在百度中搜到很多的记录: https://www.baidu.com/s?wd=prettier%20%E5%87%BD%E6%95%B0%E7%A9%BA%E6%A0%BC "prettier.spaceBeforeFunctionParen": true, // react的jsx让>与结束标签同行 "prettier.jsxBracketSameLine": true, "prettier.bracketSpacing": false, // 去掉数组内部前后的空格 "prettier.semi": false, // 不要给语句加; "prettier.singleQuote": true, // 采用单引号 "prettier.trailingComma": "none", // 不要尾随逗号, "prettier.printWidth": 80, // 每行超过80列就换行 // 在.js中,写div按下tab就可以自动补全,而不需要写<div再补全 "emmet.includeLanguages": { "javascript": "javascriptreact" } }
4.修改.eslintrc.js
module.exports = { env: { browser: true, es2021: true, node: true }, extends: [plugin:react/recommended, standard], parser: @typescript-eslint/parser, parserOptions: { ecmaFeatures: { jsx: true }, ecmaVersion: 12 }, plugins: [react, @typescript-eslint, react-hooks], rules: { react/react-in-jsx-scope: off, no-use-before-define: off, // 检查 Hooks 的使用规则 react-hooks/rules-of-hooks: error, // 检查依赖项的声明 react-hooks/exhaustive-deps: warn } }
做完这些最好重启一下vscode,然后你就会发现你的代码可以自动格式化了
上一篇:
通过多线程提高代码的执行效率例子