vue项目及uni-app项目配置eslint+prettier+husky+stylelint+lint-staged

安装依赖

npm install eslint babel-eslint eslint-plugin-vue husky lint-staged prettier @vue/eslint-config-prettier eslint-plugin-prettier stylelint stylelint-config-prettier stylelint-config-standard stylelint-order -D

其中包含了eslint、prettier、lint-staged、husky、stylelint。eslint和prettier有部分语法是冲突的,可根据个人需要选择安装。如果觉得npm太慢也可使用cnpm安装。

配置eslint

  • 在项目根目录新建.eslinttrc.js
module.exports = {
    root: true,
    env: {
        browser: true,
        node: true,
        es6: true,
    },
    // 配置js全局变量,因为是uni-app,全局的uni是不需要引入的,还有5+的plus对象
    globals: {
        uni: 'readonly',
        plus: 'readonly',
        wx: 'readonly',
    },
    // 可根据个人喜好选择,个人比较喜欢prettier配合vs code格式化html代码,安利一波!!
    extends: ['plugin:vue/essential', 'eslint:recommended', '@vue/prettier'],
    parserOptions: {
        parser: 'babel-eslint',
    },
    rules: {
        // 'prettier/prettier': 'error',
        'no-console': [
            'warn',
            {
                allow: ['warn', 'error'],
            },
        ],
        'no-eval': 'error',
        'no-alert': 'error',
        'vue/max-attributes-per-line': [
            0,
            {
                singleline: 10,
                multiline: {
                    max: 1,
                    allowFirstLine: false,
                },
            },
        ],
        'vue/singleline-html-element-content-newline': 'off',
        'vue/multiline-html-element-content-newline': 'off',
        'vue/name-property-casing': ['error', 'PascalCase'],
        'vue/no-v-html': 'off',
        'accessor-pairs': 2,

        'block-spacing': [2, 'always'],
        'brace-style': [
            2,
            '1tbs',
            {
                allowSingleLine: true,
            },
        ],
        // 属性驼峰命名
        camelcase: [
            0,
            {
                properties: 'always',
            },
        ],
        'comma-dangle': [2, 'only-multiline'],
        'comma-style': [2, 'last'],
        'constructor-super': 2,
        curly: [2, 'multi-line'],
        'dot-location': [2, 'property'],
        'eol-last': 2,
        eqeqeq: [
            'warn',
            'always',
            {
                null: 'ignore',
            },
        ],
        'generator-star-spacing': [
            2,
            {
                before: true,
                after: true,
            },
        ],
        'handle-callback-err': [2, '^(err|error)$'],
        'jsx-quotes': [2, 'prefer-single'],
        'new-cap': [
            2,
            {
                newIsCap: true,
                capIsNew: false,
            },
        ],
        'new-parens': 2,
        'no-array-constructor': 2,
        'no-caller': 2,
        'no-class-assign': 2,
        'no-cond-assign': 2,
        'no-const-assign': 2,
        'no-control-regex': 0,
        'no-delete-var': 2,
        'no-dupe-args': 2,
        'no-dupe-class-members': 2,
        'no-dupe-keys': 2,
        'no-duplicate-case': 2,
        'no-empty-character-class': 2,
        'no-empty-pattern': 2,
        'no-ex-assign': 2,
        'no-extend-native': 2,
        'no-extra-bind': 2,
        'no-extra-boolean-cast': 2,
        'no-extra-parens': [2, 'functions'],
        'no-fallthrough': 2,
        'no-floating-decimal': 2,
        'no-func-assign': 2,
        'no-implied-eval': 2,
        'no-inner-declarations': [2, 'functions'],
        'no-invalid-regexp': 2,
        'no-irregular-whitespace': 2,
        'no-iterator': 2,
        'no-label-var': 2,
        'no-labels': [
            2,
            {
                allowLoop: false,
                allowSwitch: false,
            },
        ],
        'no-lone-blocks': 2,
        'no-mixed-spaces-and-tabs': 1,
        'no-multi-spaces': 2,
        'no-multi-str': 2,

        'no-native-reassign': 2,
        'no-negated-in-lhs': 2,
        'no-new-object': 2,
        'no-new-require': 2,
        'no-new-symbol': 2,
        'no-new-wrappers': 2,
        'no-obj-calls': 2,
        'no-octal': 2,
        'no-octal-escape': 2,
        'no-path-concat': 2,
        'no-proto': 2,
        'no-redeclare': 2,
        'no-regex-spaces': 2,
        'no-return-assign': [2, 'except-parens'],
        'no-self-assign': 2,
        'no-self-compare': 2,
        'no-sequences': 2,
        'no-shadow-restricted-names': 2,
        'no-spaced-func': 2,
        'no-sparse-arrays': 2,
        'no-this-before-super': 2,
        'no-throw-literal': 2,
        'no-trailing-spaces': 0,
        'no-undef': 2,
        'no-undef-init': 2,
        'no-unexpected-multiline': 2,
        'no-unmodified-loop-condition': 2,
        'no-unneeded-ternary': [
            2,
            {
                defaultAssignment: false,
            },
        ],
        'no-unreachable': 2,
        'no-unsafe-finally': 2,
        'no-unused-vars': [
            2,
            {
                vars: 'all',
                args: 'none',
            },
        ],
        'no-useless-call': 2,
        'no-useless-computed-key': 2,
        'no-useless-constructor': 2,
        'no-useless-escape': 0,
        'no-whitespace-before-property': 2,
        'no-with': 2,
        'one-var': [
            2,
            {
                initialized: 'never',
            },
        ],
        'operator-linebreak': [
            2,
            'after',
            {
                overrides: {
                    '?': 'before',
                    ':': 'before',
                },
            },
        ],
        'padded-blocks': [2, 'never'],
        quotes: [
            2,
            'single',
            {
                avoidEscape: true,
                allowTemplateLiterals: true,
            },
        ],
        'semi-spacing': [
            2,
            {
                before: false,
                after: true,
            },
        ],

        'space-in-parens': [2, 'never'],
        'space-infix-ops': 1,
        'space-unary-ops': [
            0,
            {
                words: true,
                nonwords: false,
            },
        ],
        'template-curly-spacing': [2, 'never'],
        'use-isnan': 2,
        'valid-typeof': 2,
        'wrap-iife': [2, 'any'],
        'yield-star-spacing': [2, 'both'],
        yoda: [2, 'never'],
        'prefer-const': 2,
        'array-bracket-spacing': [2, 'never'],
        'no-prototype-builtins': 0,
        // 自定义开始
        'vue/html-indent': 0,
        'vue/html-closing-bracket-newline': 0,
        'vue/html-self-closing': 0,
        indent: 0,
        // 句尾分号
        semi: 0,
        'comma-spacing': 0,
        'space-before-blocks': 0,
        'keyword-spacing': 0,
        'key-spacing': 0,
        'no-multiple-empty-lines': 0,
        'spaced-comment': 0,
        'space-before-function-paren': 0,
        'arrow-spacing': 0,
        'object-curly-spacing': 0,
    },
}

配置prettier

在项目根目录新建prettier.config.js, pretter主要用于提交代码检查时统一格式。

module.exports = {
    // 行宽 default:80
    printWidth: 100,
    // tab 宽度 default:2
    tabWidth: 4,
    // 使用 tab 键 default:false
    useTabs: false,
    // 语句行末是否添加分号 default:true
    semi: false,
    // 是否使用单引号 default:false
    singleQuote: true,
    // 对象需要引号在加 default:"as-needed"
    quoteProps: 'as-needed',
    // jsx单引号 default:false
    jsxSingleQuote: true,
    // 最后一个对象元素加逗号 default:"es5"
    trailingComma: 'es5',
    // 在对象字面量声明所使用的的花括号后({)和前(})输出空格 default:true
    bracketSpacing: true,
    // 将 > 多行 JSX 元素放在最后一行的末尾,而不是单独放在下一行(不适用于自闭元素)。default:false
    jsxBracketSameLine: false,
    // (x) => {} 是否要有小括号 default:"always"
    arrowParens: 'always',
    // default:0
    rangeStart: 0,
    // default:Infinity
    rangeEnd: Infinity,
    // default:false
    insertPragma: false,
    // default:false
    requirePragma: false,
    // 不包装 markdown text default:"preserve"
    proseWrap: 'never',
    // HTML空白敏感性 default:"css"
    htmlWhitespaceSensitivity: 'strict',
    // 在 *.vue 文件中 Script 和 Style 标签内的代码是否缩进 default:false
    vueIndentScriptAndStyle: true,
    // 末尾换行符 default:"lf"
    endOfLine: 'auto',
    // default:"auto"
    embeddedLanguageFormatting: 'auto',
    overrides: [
        {
            files: '*.md',
            options: {
                tabWidth: 2,
            },
        },
    ],
}

配置stylelint

在项目根目录新建stylelint.config.js

module.exports = {
  root: true,
  plugins: ['stylelint-order'],
  extends: ['stylelint-config-standard', 'stylelint-config-prettier'],
  rules: {
    'selector-pseudo-class-no-unknown': [
      true,
      {
        ignorePseudoClasses: ['global'],
      },
    ],
    'at-rule-no-unknown': [
      true,
      {
        ignoreAtRules: ['function', 'if', 'each', 'include', 'mixin', 'for'],
      },
    ],
    'no-duplicate-selectors': null,
    'no-empty-source': null,
    'unicode-bom': 'never',
    'no-descending-specificity': null,
    'font-family-no-missing-generic-family-keyword': null,
    'declaration-colon-space-after': 'always-single-line',
    'declaration-colon-space-before': 'never',
    'declaration-block-trailing-semicolon': 'always',
    'rule-empty-line-before': [
      'always',
      {
        ignore: ['after-comment', 'first-nested'],
      },
    ],
    'property-no-unknown': [
      true,
      {
        ignoreProperties: ['lines'],
      },
    ],
    'media-feature-name-no-unknown': [
      true,
      {
        ignoreMediaFeatureNames: 'min-device-pixel-ratio',
      },
    ],
    'unit-no-unknown': [
      true,
      {
        ignoreUnits: ['rpx'],
      },
    ],
    'selector-pseudo-element-no-unknown': [
      true,
      {
        ignorePseudoElements: ['v-deep'],
      },
    ],
    // 指定声明块内属性的字母顺序
    'order/properties-order': [
      'position',
      'top',
      'right',
      'bottom',
      'left',
      'z-index',
      'display',
      'float',
      'width',
      'height',
      'max-width',
      'max-height',
      'min-width',
      'min-height',
      'padding',
      'padding-top',
      'padding-right',
      'padding-bottom',
      'padding-left',
      'margin',
      'margin-top',
      'margin-right',
      'margin-bottom',
      'margin-left',
      'margin-collapse',
      'margin-top-collapse',
      'margin-right-collapse',
      'margin-bottom-collapse',
      'margin-left-collapse',
      'overflow',
      'overflow-x',
      'overflow-y',
      'clip',
      'clear',
      'font',
      'font-family',
      'font-size',
      'font-smoothing',
      'osx-font-smoothing',
      'font-style',
      'font-weight',
      'hyphens',
      'src',
      'line-height',
      'letter-spacing',
      'word-spacing',
      'color',
      'text-align',
      'text-decoration',
      'text-indent',
      'text-overflow',
      'text-rendering',
      'text-size-adjust',
      'text-shadow',
      'text-transform',
      'word-break',
      'word-wrap',
      'white-space',
      'vertical-align',
      'list-style',
      'list-style-type',
      'list-style-position',
      'list-style-image',
      'pointer-events',
      'cursor',
      'background',
      'background-attachment',
      'background-color',
      'background-image',
      'background-position',
      'background-repeat',
      'background-size',
      'border',
      'border-collapse',
      'border-top',
      'border-right',
      'border-bottom',
      'border-left',
      'border-color',
      'border-image',
      'border-top-color',
      'border-right-color',
      'border-bottom-color',
      'border-left-color',
      'border-spacing',
      'border-style',
      'border-top-style',
      'border-right-style',
      'border-bottom-style',
      'border-left-style',
      'border-width',
      'border-top-width',
      'border-right-width',
      'border-bottom-width',
      'border-left-width',
      'border-radius',
      'border-top-right-radius',
      'border-bottom-right-radius',
      'border-bottom-left-radius',
      'border-top-left-radius',
      'border-radius-topright',
      'border-radius-bottomright',
      'border-radius-bottomleft',
      'border-radius-topleft',
      'content',
      'quotes',
      'outline',
      'outline-offset',
      'opacity',
      'filter',
      'visibility',
      'size',
      'zoom',
      'transform',
      'box-align',
      'box-flex',
      'box-orient',
      'box-pack',
      'box-shadow',
      'box-sizing',
      'table-layout',
      'animation',
      'animation-delay',
      'animation-duration',
      'animation-iteration-count',
      'animation-name',
      'animation-play-state',
      'animation-timing-function',
      'animation-fill-mode',
      'transition',
      'transition-delay',
      'transition-duration',
      'transition-property',
      'transition-timing-function',
      'background-clip',
      'backface-visibility',
      'resize',
      'appearance',
      'user-select',
      'interpolation-mode',
      'direction',
      'marks',
      'page',
      'set-link-source',
      'unicode-bidi',
      'speak',
    ],
  },
}

配置lint-staged

在项目根目录新建lint-staged.config.js, 具体配置含义可自行google

module.exports = {
    '*.{js,jsx,ts,tsx,vue}': ['prettier --write', 'eslint --fix'],
    '{!(package)*.json,*.code-snippets,.!(browserslist)*rc}': ['prettier --write--parser json'],
    'package.json': ['prettier --write'],
    '*.vue': ['prettier --write', 'stylelint --fix'],
    '*.{scss,less,styl,css,html}': ['stylelint --fix', 'prettier --write'],
    '*.md': ['prettier --write'],
}

配置package.json

在配置中添加以下配置

"scripts": {
    "lint:eslint": "eslint --fix --ext \"./**/*.{vue,less,css,scss}\"",
    "lint:prettier": "prettier --write --loglevel warn \"./**/*.{js,json,tsx,css,less,scss,vue,html,md}\"",
    "lint:stylelint": "stylelint --fix \"**/*.{vue,less,postcss,css,scss}\" --cache --cache-location node_modules/.cache/stylelint/",
    "lint-staged": "lint-staged",
    "lint-staged:js": "eslint --ext .js,.jsx,.ts,.tsx ",
}
// husky的其他配置可自行添加,这里只配置了git提交运行lint-staged
"husky": {
    "hooks": {
        "pre-commit": "lint-staged"
    }
},

如不需要在git提交时自动修复代码可将husky配置中的lint-staged改为lint-staged:js,

配置代码检测忽略目录

.eslintignore

可自行根据需要添加

unpackage
node_modules
uview-ui

.prettierignore

# 忽略打包的文件
unpackage
# 忽略uni-app官方的组件库错误和警告,官方的竟然通不过...
uni-**
uview-ui

.gitignore

.DS_Store
node_modules/
unpackage/
dist/

# local env files
.env.local
.env.*.local

# Log files
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Editor directories and files
.project
.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw*

配置完成

  • 运行npm run lint-staged没问题的话就欧克了

最后附上个人vs code Eslint插件及Vetur配置

"editor.codeActionsOnSave": {
    "source.fixAll.eslint": true,
},
"eslint.codeAction.showDocumentation": {
"enable": true
},
"eslint.format.enable": true,
"eslint.probe": [
    "javascript",
    "javascriptreact",
    "typescript",
    "typescriptreact",
    "html",
    "vue",
    "markdown",
    "css"
],
"[javascript]": {
    "editor.defaultFormatter": "dbaeumer.vscode-eslint"
},
"vetur.format.defaultFormatter.js": "none",
"vetur.format.options.tabSize": 4,
"[vue]": {
    "editor.defaultFormatter": "dbaeumer.vscode-eslint"
},
"editor.tabSize": 4,
"auto-close-tag.excludedTags": [
    "area",
    "base",
    "br",
    "col",
    "command",
    "embed",
    "hr",
    "img",
    "input",
    "keygen",
    "link",
    "meta",
    "param",
    "source",
    "track",
    "wbr"
],
"editor.fontSize": 14,
"editor.lineHeight": 22,
"eslint.debug": true,
"eslint.lintTask.enable": true,
"eslint.alwaysShowStatus": true,
"editor.detectIndentation": false,
"diffEditor.ignoreTrimWhitespace": false,
"terminal.integrated.shell.windows": "C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe",
"files.associations": {
    "*.json": "jsonc"
},

参考:https://blog.csdn.net/a1647800606/article/details/106344616/https://codechina.csdn.net/mirrors/PanJiaChen/vue-admin-template/-/tree/master

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,753评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,668评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,090评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,010评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,054评论 6 395
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,806评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,484评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,380评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,873评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,021评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,158评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,838评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,499评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,044评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,159评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,449评论 3 374
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,136评论 2 356

推荐阅读更多精彩内容