第一步:
插件安裝:
npm i -D eslint-plugin-prettier
eslint-plugin-prettier插件會調用prettier對你的代碼風格進行檢查,其原理是先使用prettier對你的代碼進行格式化,然后與格式化之前的代碼進行對比,如果過出現了不一致,這個地方就會被prettier進行標記。
npm i -D eslint-config-prettier
通過使用eslint-config-prettier配置,能夠關閉一些不必要的或者是與prettier沖突的lint選項。這樣我們就不會看到一些error同時出現兩次。使用的時候需要確保,這個配置在extends的最后一項。
第二步:
配置 .eslintrc.js (cli時選擇了eslint):
module.exports = {
root: true,
env: {
browser: true,
node: true,
},
parserOptions: {
parser: 'babel-eslint',
},
extends: [
'@nuxtjs',
'plugin:nuxt/recommended',
'plugin:prettier/recommended',
'prettier',
'prettier/vue',
],
plugins: ['prettier'],
// add your custom rules here
rules: {
'nuxt/no-cjs-in-config': 'off',
indent: ['error', 4], // 4個空格縮進
/* 更多配置請戳 http://eslint.cn/docs/rules/ */
},
}
第三步:
配置 .prettierrc(在根目錄下新建.prettierrc文件,在使用eslint規則時,本地編輯器的格式化代碼會與eslint的規則沖突,這里自己配置一個.prettierrc格式化代碼的文件,約束您的代碼風格):
{
"tabWidth": 4,
// 使用tab縮進,默認false
"useTabs": false,
// 使用分號, 默認true
"semi": false,
// 使用單引號, 默認false(在jsx中配置無效, 默認都是雙引號)
"singleQuote": false,
// 行尾逗號,默認none,可選 none|es5|all
// es5 包括es5中的數組、對象
// all 包括函數對象等所有可選
"TrailingCooma": "all",
// 對象中的空格 默認true
// true: { foo: bar }
// false: {foo: bar}
"bracketSpacing": true,
// JSX標簽閉合位置 默認false
// false: <div
// className=""
// style={{}}
// >
// true: <div
// className=""
// style={{}} >
"jsxBracketSameLine": false,
// 箭頭函數參數括號 默認avoid 可選 avoid| always
// avoid 能省略括號的時候就省略 例如x => x
// always 總是有括號
"arrowParens": "avoid"
}
第四步:
配置webpack: (在nuxt.config.js中的build里對webpack進行擴展配置):
build: {
extend(config, ctx) {
// Run ESLint on save
if (ctx.isDev && ctx.isClient) {
config.module.rules.push({
enforce: 'pre',
test: /\.(js|vue)$/,
loader: 'eslint-loader',
exclude: /(node_modules)/,
options: {
fix: true,
},
})
}
},
},
我們項目是在webpack中引入eslint-loader來啟動eslint的,所以我們只要稍微修改webpack的配置,就能在啟動webpack-dev-server的時候,每次保存代碼同時自動對代碼進行格式化。
eslint-plugin-prettier插件會調用prettier對你的代碼風格進行檢查,其原理是先使用prettier對你的代碼進行格式化,然后與格式化之前的代碼進行對比,如果過出現了不一致,這個地方就會被prettier進行標記,最后eslint自動fix按照prettier的規范修復error代碼。
