非vue/cli创建的vue2项目引入eslint和prettier最佳实践总结

952 阅读4分钟

前言

在多人协同开发的过程中,为了保持代码风格的统一和一定程度上的代码检测,对于vue项目,现在社区的普遍做法是用通过esLint + prettier的方式解决的。

esLint的作用是:

进行代码检测,提前发现一些错误

prettier的作用是:

统一代码风格,便于多人协同开发

本文主要针对那些非vue/cli创建的vue项目(vue/cli的项目在创建的时候可以非常方便的进行配置),这些项目可能没有集成eslintprettier或者之前就存在一些问题。

最佳实践方案

  1. 通过eslint-plugin-vue包对.vue文件进行eslint检查
  2. 通过@/vue/prettier.vue文件进行风格统一以及解决prettiereslint自带格式化规则的冲突(吐槽一下,eslint你要么就全做,做一部分格式化干嘛!!)。
  3. 通过命令对原来的整个项目进行格式化修复
  4. 通过vscode 配置实现保存时做格式化处理对不符合规则的部分进行标记

【步骤1和2的实践】

  1. 先安装所需的几个个包(默认babel相关的包已经安装好了):
npm install eslint //试验用的版本的是4.19.1
npm install prettier
npm install eslint-plugin-vue --save-dev
npm install @vue/eslint-config-prettier
npm install eslint-plugin-prettier

ps: 其中由于目前版本的eslint-plugin-prettier存在问题(通过命令修复报错context.getPhysicalFilename is not a function),可以先指定塔的版本为3.1.4,eslint如果有问题也可以用我这个版本

//pageage.json
{
    devDependencies: {
        "eslint": "^4.19.1",
        "eslint-plugin-prettier": "^3.1.4",
        "eslint-plugin-vue": "^4.5.0",
   }
}

  1. 配置项目根目录下的.eslintrc.js文件(没有就创建一个),内容如下:
module.exports = {
  root: true,
  parserOptions: {
    parser: 'babel-eslint',
    sourceType: 'module'
  },
  env: {
    //这里填你需要的环境
    browser: true,
    mocha: true,
    node: true
  },
  globals: {
    //向ESLint规则中添加全局变量
    expect: true,
    jest: true,
    sinon: true,
    td: true,
    wx: true
  },
  extends: [
    'plugin:vue/essential', //eslint-plugin-vue 建议的配置
    'eslint:recommended', //eslint规则方案
    '@vue/prettier'
  ],
  parserOptions: {
    parser: 'babel-eslint'
  },
  rules: {
    //自定义覆盖原来的规则
    'no-unused-vars': 'warn', //未使用变量采用告警的形式
    'no-empty': 'off', // 关闭对空作用域的检查
    'no-console': 'off', //关闭对console的检查
    'vue/no-async-in-computed-properties': 0,
    'vue/no-side-effects-in-computed-properties': 0,
    'vue/max-attributes-per-line': 0,
    'template-curly-spacing': 'off', //大括号2侧的空格
    indent: 'off', //缩进
    'no-debugger': 'off',
    'space-before-function-paren': 'off'
  }
}

  1. 配置项目根目录下的.prettierrc.js文件(没有就创建一个),内容如下:
// wiki: https://wiki.dxy.net/pages/viewpage.action?pageId=185308903
module.exports = {
  // 单行字符长度
  printWidth: 100,
  // 是否添加分号
  semi: false,
  // 是否使用单引号
  singleQuote: true,
  // 多行数组是否需要尾部追加逗号 es5 语法需要
  trailingComma: 'none',
  endOfLine: 'auto', //解决window和linux下换行报错问题
}

【通过命令对原来的整个项目进行格式化修复】

  1. 在package.json中写入以下内容
// package.json
  "scripts": {
    "lint": "eslint --ext .js,.vue src",
    "fix": "eslint --ext .js,.vue src --fix",
    "prettier:fix": "prettier --write \"src/**/*.{js,jsx,ts,tsx,json,css,scss,less,md,vue}\"",
    "format": "npm run prettier:fix && npm run fix",
  },

  1. 运行命令

npm run format

ps: 如果出现报错那么就先执行npm run prettier:fix,再执行npm run fix

这个时候,一些基础修复已经被eslintprettier完成了,还有一些错误需要手动修复,如果有些错误不想修复可以在.eslintrc.js文件的rules字段中进行关闭或者编辑.prettierrc.js文件,具体可以参照上面的代码。

【通过vscode 配置实现保存时做格式化处理对不符合规则的部分进行标记

vscode的配置优先级是:

项目路径/.vscode/settings.json > 用户路径/.vscode/settings.json > 默认配置

  1. 我这里为了所有的工程带来统一的开发体验,这里直接更改用户路径/.vscode/settings.json(实际上可以给每个项目下新建一个.vscode/settings.json文件夹后写上同样的配置,如果遇到配置不生效注意上面说的优先级的问题),内容如下:
{
  // 格式化配置--begin
  "eslint.probe": [
    "javascript",
    "javascriptreact",
    "typescript",
    "typescriptreact",
    "html",
    "vue"
  ],
  "eslint.options": {
    "extensions": ["*.html", "*.vue", "*.ts", "*.tsx", "*.js"],
    "configFile": ".eslintrc.js" // 改为你的文件路径
  },
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "editor.formatOnSave": true,
  "eslint.codeAction.showDocumentation": {
    "enable": true
  },
  "eslint.workingDirectories": ["./"],
  "eslint.codeAction.disableRuleComment": {},
  "[javascript]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "[javascriptreact]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode",
    "editor.showUnused": true
  },
  "[vue]": {
    //vue的默认配置插件
    // "editor.defaultFormatter": "esbenp.prettier-vscode",
    "editor.showUnused": true //未使用变量置灰
  },
  "[json]": {
    "editor.defaultFormatter": "esbenp.prettier-vscode"
  },
  "vetur.format.enable": false,
  "vetur.validation.template": false,
  "vetur.validation.script": false,
  "vetur.validation.style": false,
  // 格式化配置--end
  "files.eol": "\n",
  "editor.renderWhitespace": "all",
  "files.trimTrailingWhitespace": true,
  "files.associations": {
    "*.js": "javascriptreact",
    "*.cjson": "jsonc",
    "*.vue": "vue"
  },
  "emmet.triggerExpansionOnTab": true,
  "http.proxySupport": "off",
  "javascript.updateImportsOnFileMove.enabled": "always",
  "json.schemas": [],
  "emmet.includeLanguages": {
    "wxml": "html"
  },
  "explorer.compactFolders": false,
  "git.path": "",
  "window.zoomLevel": 2,
  "editor.foldingMaximumRegions": 50000,
  "editor.largeFileOptimizations": false
}

  1. 安装vscode 扩展

image.png

结语

经过这一系列的操作,达到了下面3个效果:

1. 代码检测

2. 风格统一

3. vcode的所有操作(保存时格式化以及标记能力)都是跟着项目走