vue2代码规范eslint配置

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vue2代码规范eslint配置

Caroline皮皮   2022-09-28 我要评论

正文

eslint用于代码检查,prettier用于代码格式化,具体操作如下

1.安装以下eslint插件

安装以下eslint插件,并增加.eslintrc.js配置文件,.eslintignore配置忽略检查的文件

(1)eslint

用于检查和标示出ECMAScript/JavaScript代码规范问题工具。

(2)@babel/eslint-parser

简而言之就是一个解析器,允许您使用ESLint对所有有效的Babel代码进行检查。

ESLint允许使用自定义解析器,当使用此插件时,代码会被Babel解析器解析,并且生成的AST被转换成一个ESLint可以理解的符合ESTree的结构,所有的位置信息如行列也会保留,因此可以轻松的追踪错误

(3)eslint-plugin-vue

Vue.js的官方ESLint插件,即使用eslint检查.vue文件的template和script

(4)eslint-config-prettier或者@vue/eslint-config-prettier

当prettier与eslint有些规则冲突时,使用prettier的规则进行覆盖

其中@vue/cli-plugin-eslint是特别为@vue/cli&create vue setups使用而设计的

(5)@vue/cli-plugin-eslint

vue-cli的eslint 插件,检查和修复文件

1.1 .eslintrc.js文件配置

module.exports = {
  root: true, // 在根目录下寻找.eslintrc.js文件,如果当前工作区打开的项目不是在根目录,则查找.eslintrc.js文件会失败,且eslint检查也不会生效
  env: {
    node: true
  },
  extends: [
    'plugin:vue/essential',
    'eslint:recommended',
    'plugin:prettier/recommended', // 冲突时使用prettier的规则进行覆盖
  ],
  parserOptions: {
    parser: '@babel/eslint-parser'
  },
  rules: {
    'no-console': process.env.NODE_ENV === 'production' ? 'error' : 'off',
    'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
    'vue/multi-word-component-names': 'off', // 不校验组件名
    "vue/no-multiple-template-root": 0, // 不需要使用根元素包裹template的内容
  }
};

1.2 .eslintignore文件的配置

node_modules
dist

2. 安装prettier

安装prettier,并增加.prettierrc.js文件

代码格式化工具,通过.prettierrc.js文件进行配置代码规范 .prettierrc.js相关配置如下

//配置参照 http://prettier.io/docs/en/options.html
module.exports = {
    tabWidth: 2, // tab 使用两个空格
    endOfLine: "auto", // 保持现有的行尾
    useTabs: false, // 不使用制表符缩进,使用空格缩进
    semi: true, // 代码需要分号结尾
    singleQuote: true, // 单引号
    bracketSpacing: true, // 对象左右两侧需要空格
    jsxBracketSameLine: false, // html 关闭标签换行
    arrowParens: 'avoid', // 单参数的箭头函数参数不需要括号
    proseWrap: 'never', // markdown文档不换行
    trailingComma: 'none' // 结尾处不加逗号
  }

3. package.json相关代码

"devDependencies": {
  "@babel/eslint-parser": "^7.18.9",
  "@vue/cli-plugin-eslint": "^5.0.8",
  "eslint": "^7.32.0",
  "eslint-config-prettier": "^8.5.0",
  "eslint-plugin-vue": "^8.7.1",
  "prettier": "^2.7.1",
}

4. vscode的配置

(1)配置eslint、prettier插件

vscode工具栏右下角两个插件的启用状态

(2)setting.json文件的配置

{
   // 用于保存时使用进行代码格式化
    "editor.codeActionsOnSave": {
        "source.fixAll": true,
    },
    // 用于vscode右下角工具栏展示eslint标识
    "eslint.alwaysShowStatus": true,
}

5. 启动项目

由于是在老项目中增加eslint规范,所以要实现以下两点

第一,其他开发伙伴可轻松使用,需参照以下步骤

(1)确保安装eslint、prettier插件
(2)确保vscode的setting.json文件中的source.fixAll配置为true
(3)删除本地node_modules
     npm i rimraf
     rimraf node_modules
(4)npm i重新安装依赖

第二,因为旧代码有很多代码不规范,为了控制台清爽,也为了提高启动速度,需要将vue.config.js中的lintOnSave设置为false,即运行时不启用lint

以上就是代码规范配置的全部内容了,更多关于vue2代码规范eslint配置的资料请关注其它相关文章!

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们