Vue 配置.eslintrc.js .prettierrc.js vue.config.js


1 create vue demo時, 選擇如下設置:

 (*) Choose Vue version   //2
 (*) Babel
 ( ) TypeScript
 ( ) Progressive Web App (PWA) Support        
 (*) Router               //not history
 (*) Vuex
 (*) CSS Pre-processors   //less
 (*) Linter / Formatter   //ESLint + Prettier
 ( ) Unit Testing
 ( ) E2E Testing

選擇 //ESLint + Prettier之后, 會自動下載, 並安裝到依賴, 為了在其他編輯器(可能沒安裝eslint和prettier插件)中使用
右鍵使用...格式化文檔, 選擇prettier-code formatter

2 .eslintrc.js自動創建
.prettierrc.js自己寫, 根據公司提供的eslintrc

module.exports = {
root: true,
env: {
 node: true
},
//"eslint:recommended" 來啟用推薦的規則
extends: ['plugin:vue/essential', 'eslint:recommended', '@vue/prettier'],
parserOptions: {
 parser: 'babel-eslint'
},
rules: {
 'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
 'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
 'prettier/prettier': ['error', { endOfLine: 'auto' }],
 //兩個空格不要縮進
 indent: ['error', 2],
 //最大長度80 tab 2字符
 'max-len': ['error', { code: 180, tabWidth: 2 }],
 //禁止使用分號;
 semi: ['error', 'never'],
 //單引號
 quotes: ['error', 'single'],
 //末尾逗號
 'comma-dangle': ['error', 'never'],
 //unix以lf(\n)換行符結尾(默認)  window以crlf(\r\n)換行符結尾,你可以關閉此規則(不寫即關閉)
 //'linebreak-style': ['error', 'unix']
 
 // 對象中打印空格 默認always
 // always: { foo: bar }
 // never: {foo: bar}
 'object-curly-spacing': ["error", "always"],
 // 箭頭函數參數括號 默認avoid 可選 as-needed| always
 // as-needed 能省略括號的時候就省略 例如x => x
 // always 總是有括號
 'arrow-parens': ["error", "always"]
}
}



★★★★★
現在可以這樣寫"plugin:prettier/recommended"插件讓eslint的校驗規則=prettier的,不用重復寫一遍. 這也是vue現在默認的寫法
module.exports = {
root: true,
env: {
 node: true,
},
extends: [
 "plugin:vue/essential",
 "eslint:recommended",
 "plugin:prettier/recommended",
],
parserOptions: {
 parser: "@babel/eslint-parser",
},
rules: {
 "no-console": process.env.NODE_ENV === "production" ? "warn" : "off",
 "no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off",
},
};


寫.prettierrc.js

module.exports = {
//使用空格縮進
useTabs: false,
//縮進的空格數
tabWidth: 2,
//打印寬度
printWidth: 180,
//末尾分號
semi: false,
//單引號
singleQuote: true,
//末尾逗號
trailingComma: 'none',
//在 windows 操作系統中換行符通常是回車 (CR) 加換行分隔符 (LF),也就是回車換行(CRLF),
//然而在 Linux 和 Unix 中只使用簡單的換行分隔符 (LF)。
//對應的控制字符為 "\n" (LF) 和 "\r\n"(CRLF)。auto意為保持現有的行尾
endOfLine: 'auto',
 // 對象中打印空格 默認true
 // true: { foo: bar }
 // false: {foo: bar}
 bracketSpacing: true,
 // 箭頭函數參數括號 默認avoid 可選 avoid| always
 // avoid 能省略括號的時候就省略 例如x => x
 // always 總是有括號
 arrowParens: 'avoid',
 //屬性自動換行
 proseWrap:'never'
}
.prettierignore文件
dist/
src/actions

.eslintignore文件
build/*.js
config/*.js
src/assets
src
scripts/*

vue.config.js自己寫

// vue.config.js參考
const path = require('path');
const CompressionWebpackPlugin = require("compression-webpack-plugin"); // 開啟gzip壓縮, 按需引用
const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i; // 開啟gzip壓縮, 按需寫入
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin; // 打包分析
const IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV);
const resolve = (dir) => path.join(__dirname, dir);
module.exports = {
publicPath: process.env.NODE_ENV === 'production' ? '/site/vue-demo/' : '/', // 公共路徑
indexPath: 'index.html' , // 相對於打包路徑index.html的路徑
outputDir: process.env.outputDir || 'dist', // 'dist', 生產環境構建文件的目錄
assetsDir: 'static', // 相對於outputDir的靜態資源(js、css、img、fonts)目錄
lintOnSave: false, // 是否在開發環境下通過 eslint-loader 在每次保存時 lint 代碼
runtimeCompiler: true, // 是否使用包含運行時編譯器的 Vue 構建版本
productionSourceMap: !IS_PROD, // 生產環境的 source map
parallel: require("os").cpus().length > 1, // 是否為 Babel 或 TypeScript 使用 thread-loader。該選項在系統的 CPU 有多於一個內核時自動啟用,僅作用於生產構建。
pwa: {}, // 向 PWA 插件傳遞選項。
chainWebpack: config => {
 config.resolve.symlinks(true); // 修復熱更新失效
 // 如果使用多頁面打包,使用vue inspect --plugins查看html是否在結果數組中
 config.plugin("html").tap(args => {
   // 修復 Lazy loading routes Error
   args[0].chunksSortMode = "none";
   return args;
 });
 config.resolve.alias // 添加別名
   .set('@', resolve('src'))
   .set('@assets', resolve('src/assets'))
   .set('@components', resolve('src/components'))
   .set('@views', resolve('src/views'))
   .set('@store', resolve('src/store'));
 // 壓縮圖片
 // 需要 npm i -D image-webpack-loader
 config.module
   .rule("images")
   .use("image-webpack-loader")
   .loader("image-webpack-loader")
   .options({
     mozjpeg: { progressive: true, quality: 65 },
     optipng: { enabled: false },
     pngquant: { quality: [0.65, 0.9], speed: 4 },
     gifsicle: { interlaced: false },
     webp: { quality: 75 }
   });
 // 打包分析, 打包之后自動生成一個名叫report.html文件(可忽視)
 if (IS_PROD) {
   config.plugin("webpack-report").use(BundleAnalyzerPlugin, [
     {
       analyzerMode: "static"
     }
   ]);
 }
},
configureWebpack: config => {
 // 開啟 gzip 壓縮
 // 需要 npm i -D compression-webpack-plugin
 const plugins = [];
 if (IS_PROD) {
   plugins.push(
     new CompressionWebpackPlugin({
       filename: "[path].gz[query]",
       algorithm: "gzip",
       test: productionGzipExtensions,
       threshold: 10240,
       minRatio: 0.8
     })
   );
 }
 config.plugins = [...config.plugins, ...plugins];
},
css: {
 extract: IS_PROD,
 requireModuleExtension: false,// 去掉文件名中的 .module
 loaderOptions: {
     // 給 less-loader 傳遞 Less.js 相關選項
     less: {
       // `globalVars` 定義全局對象,可加入全局變量
       globalVars: {
         primary: '#333'
       }
     }
 }
},
devServer: {
   overlay: { // 讓瀏覽器 overlay 同時顯示警告和錯誤
    warnings: true,
    errors: true
   },
   host: "localhost",
   port: 8080, // 端口號
   https: false, // https:{type:Boolean}
   open: false, //配置自動啟動瀏覽器
   hotOnly: true, // 熱更新
   // proxy: 'http://localhost:8080'  // 配置跨域處理,只有一個代理
   proxy: { //配置多個跨域
     "/api": {
       target: "http://172.11.11.11:7071",
       changeOrigin: true,
       // ws: true,//websocket支持
       secure: false,
       pathRewrite: {
         "^/api": "/"
       }
     },
     "/api2": {
       target: "http://172.12.12.12:2018",
       changeOrigin: true,
       //ws: true,//websocket支持
       secure: false,
       pathRewrite: {
         "^/api2": "/"
       }
     },
   }
 }
}

3 報錯Failed to load config “prettier“ to extend from.?
解決方案:
npm i eslint prettier-eslint eslint-config-prettier --save-dev //注意版本問題
原因:
I just had this error: I was manually installing the prettier modules, and only had eslint-plugin-prettier but not eslint-config-prettier.

Failed to load config “@vue/prettier“ to extend from
解決方案:
@vue/prettier改為prettier
原因還不知道, @vue/prettier在@vue/下沒找到


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM