Eslint配置详解(二)

162 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第6天,点击查看活动详情

.eslintignore

.eslintignore 的作用跟 .gitignore类似,作用是为了指定不检查的目录,新建一个.eslintignore, 默认模板为

dist
node_modules
test
public

.eslintrc.js

.eslintrc 是eslint的配置项,在上一章讲的常用配置项便是.eslintrc的key

以上一章的配置,能延伸出一个常用的简单模板

module.exports = {
    root: true,
    parser: 'vue-eslint-parser',
    parserOptions: {
      parser: 'babel-eslint',
      sourceType: 'module',
    },
    globals: {
      Atomics: 'readonly',
      SharedArrayBuffer: 'readonly',
      process: true,
      common: true,
      module: true,
      require: true
    },
    env: {
      browser: true,
    },
    extends: ['eslint:recommended', 'plugin:vue/essential'],
    // required to lint *.wpy files
    plugins: ['html', 'vue'],
    settings: {
      'html/html-extensions': ['.html', '.wpy', '.moe'],
    },
    // add your custom rules here
    rules: {
      semi: [2, 'always'], //语句强制分号结尾
      'arrow-parens': 0, //箭头函数用小括号括起来
      'generator-star-spacing': 0, //生成器函数*的前后空格
      'no-debugger': 0, //禁止使用debugger
      "space-before-function-paren": ["error", {
          "anonymous": "always",
          "named": "always",
          "asyncArrow": "always"
      }], //函数定义时括号前面要有空格
      'no-self-compare': 2, // 不能比较自身
      quotes: ['error', 'single'], // 如果不是单引号,则报错
      'no-var': 1, //禁用var,用let和const代替
    },
  };

碰到的问题

其中

"space-before-function-paren": ["error", {
      "anonymous": "always",
      "named": "always",
      "asyncArrow": "always"
  }]

这样的写法是当时遇见一个坑,vscode自动保存的时候,会把单引号变双引号,即使是在根目录去做prettier的配置依然不行,于是最后为了不耽误开发,便在本地对src进行了屏蔽,并在package.json中去配置

  "scripts": {
    "lint": "eslint --fix --ext .js,.vue src",
  },

然后开发完后对项目执行npm run lint

prettier

在vscode中安装prettier,在项目根目录新建 prettier.config.js

module.exports = {
  printWidth: 200, // 每行代码长度(默认80tabWidth: 2, // 每个tab相当于多少个空格(默认2useTabs: false, // 是否使用tab进行缩进(默认falsesingleQuote: true, // 使用单引号(默认falsesemi: true, // 声明结尾使用分号(默认true)
  trailingComma: 'all', // 多行使用拖尾逗号(默认none)
  bracketSpacing: true, // 对象字面量的大括号间使用空格(默认truejsxBracketSameLine: true, // 多行JSX中的>放置在最后一行的结尾,而不是另起一行(默认falsearrowParens: 'avoid', // 只有一个参数的箭头函数的参数是否带圆括号(默认avoid)
};

prettier会根据配置项去自动格式化项目,以上配置仅做参考