1.配置eslint
npm install --save-dev eslint eslint-plugin-vue@next
2.package.json添加下面的配置
"eslintConfig": { "root": true, "env": { "node": true }, "extends": [ "plugin:vue/vue3-essential", "eslint:recommended" ], "parserOptions": { "parser": "babel-eslint" }, "rules": {} },
3.添加.eslintrc.js
module.exports = { extends: ['plugin:vue/strongly-recommended', 'plugin:prettier/recommended'], rules: { 'prettier/prettier': 'error', }, };
4.添加prettier.config
module.exports = { printWidth: 80, // 每行代碼長度(默認80) tabWidth: 2, // 每個tab相當於多少個空格(默認2) useTabs: false, // 是否使用tab進行縮進(默認false) singleQuote: true, // 使用單引號(默認false) semi: true, // 聲明結尾使用分號(默認true) trailingComma: 'all', // 多行使用拖尾逗號(默認none) bracketSpacing: true, // 對象字面量的大括號間使用空格(默認true) jsxBracketSameLine: false, // 多行JSX中的>放置在最后一行的結尾,而不是另起一行(默認false) arrowParens: 'avoid', // 只有一個參數的箭頭函數的參數是否帶圓括號(默認avoid) };
5.package.json配置commit提交前的鈎子
"husky": { "hooks": { "pre-commit": "lint-staged", "prepare-commit-msg": "exec < /dev/tty && git cz --hook || true" } }, "lint-staged": { "*.js": [ "prettier --write", "vue-cli-service lint", "git add" ], "*.vue": [ "prettier --write", "vue-cli-service lint", "git add" ] },
6. pageckage.json格式化自動命令配置
"format": "prettier --write \"src/**/*.js\" \"src/**/*.vue\" \"*json\" \"*.config.js\" \"*.eslintrc.js\""
終端執行命令
npm run format //or yarn format
7.package.json 配置lint檢查
"lint": "vue-cli-service lint",
終端執行命令
yarn lint //or npm run lint
8.開發環境中開啟lint
第一種方式基於vue-cli3.0創建的需要在vue.config.js中
lintOnSave: 'error',
第二種方式在webpack中配置:
config/index.js中添加配置
dev: { useEslint: true, }
build/webpack.base.config.js
const createLintingRule = () => ({ test: /\.(js|vue)$/, loader: 'eslint-loader', enforce: 'pre', include: [resolve('src'), resolve('test')], options: { formatter: require('eslint-friendly-formatter'), emitWarning: !config.dev.showEslintErrorsInOverlay, fix: true, } })