老项目中如何使用eslint和prettier

143 阅读2分钟

安装依赖

npm eslint,prettier需要安装在开发环境配置下

npm instll eslint prettier -D

工作区vscode/setting.json更新配置代码

{
   "files.autoSave": "afterDelay",
    "workbench.colorTheme": "Visual Studio Dark",
    "editor.fontSize": 20,
    "explorer.confirmDelete": false,
    "security.workspace.trust.untrustedFiles": "open",
    "[html]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[css]":{
      "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "editor.tabSize":2,
    "eslint.autoFixOnSave": true, //  启用保存时自动修复,默认只支持.js文件
    "editor.codeActionsOnSave": {
      "source.fixAll.eslint": true // 保存时使用eslint校验文件
    },
    "editor.unicodeHighlight.ambiguousCharacters": false,
    "window.zoomLevel": 0,
    "[vue]": {
      "editor.defaultFormatter": "esbenp.pretter-vscode"
    },
    "[javascript]": {
      "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
 
}

.eslintrc.js配置

{
  "printWidth": 220,
  "tabWidth": 2,
  "useTabs": false,
  "semi": true,
  "singleQuote": true,
  "quoteProps": "as-needed",
  "jsxSingleQuote": false,
  "trailingComma": "es5",
  "bracketSpacing": true,
  "bracketSameLine": false,
  "arrowParens": "always",
  "requirePragma": false,
  "insertPragma": false,
  "proseWrap": "preserve",
  "htmlWhitespaceSensitivity": "ignore",
  "vueIndentScriptAndStyle": false,
  "endOfLine": "lf"
}

prettier配置

{
  "printWidth": 220,  // 超过最大值换行
  "tabWidth": 2,  // 缩进字节数
  "useTabs": false,  // 缩进不使用tab,使用空格
  "semi": true,  // 句尾添加分号
  "singleQuote": true,  // 使用单引号代替双引号
  "quoteProps": "as-needed",
  "jsxSingleQuote": false,  // 在jsx中使用单引号代替双引号 "prettier.parser": "babylon", // 格式化的解析器,默认是babylon
  "trailingComma": "es5", // 在对象或数组最后一个元素后面是否加逗号(在ES5中加尾逗号)
  "bracketSpacing": true, // 在对象,数组括号与文字之间加空格 "{ foo: bar }"
  "bracketSameLine": false, // 在jsx中把'>' 是否单独放一行
  "arrowParens": "always",// (x) => {} 箭头函数参数只有一个时是否要有小括号。avoid:省略括号
  "requirePragma": false,
  "insertPragma": false,
  "proseWrap": "preserve", // 默认值。因为使用了一些折行敏感型的渲染器(如GitHub comment)而按照markdown文本样式进行折行
  "htmlWhitespaceSensitivity": "ignore",
  "vueIndentScriptAndStyle": false,
  "endOfLine": "lf"   // 结尾是 \n \r \n\r auto  window 系统这里有坑
}

设置到packjson.script中

  "scripts": {
    "lint:css": "stylelint src/**/*.{css,scss,html,vue} --fix",
    "lint:js": "vue-cli-service lint",
    "lint:eslint": "eslint --cache src/**/*.{vue,js} --fix",
    "lint:prettier": "prettier --write src/**/*.{js,json,css,less,scss,vue}",
    "lint": "npm run lint:eslint && npm run lint:prettier"
  },

注意:这个不是ctrl+s后就生效,需要通过命令行才能生效

npm run lint

image.png

由于历史原因,windows下和linux下的文本文件的换行符不一致。 Windows在换行的时候,同时使用了回车符CR(carriage-return character)和换行符LF(linefeed character) 而Mac和Linux系统,仅仅使用了换行符LF 老版本的Mac系统使用的是回车符CR 如果是windows系统,文件编码是UTF-8且包含中文,最好全局将autocrlf设置为false

npm i eslint prettier-eslint eslint-config-prettier --save-dev
git config --global core.autocrlf false