vscode中vue cli3+typescript項目如何保存自動格式化代碼并修復(fù)eslint錯誤

背景

操作系統(tǒng):win10
編輯器:vscode
項目:vue cli3 + typescript
目的:配置保存時自動格式化代碼并且修復(fù)可修復(fù)的eslint語法錯誤

生成項目配置

命令:

vue create <項目名>

linter配置選擇ESLint+Prettier

Vue CLI v3.6.3
┌───────────────────────────┐
│  Update available: 4.0.5  │
└───────────────────────────┘
? Please pick a preset: Manually select features
? Check the features needed for your project: Babel, TS, Router, Vuex, CSS Pre-processors, Linter, Unit
? Use class-style component syntax? Yes
? Use Babel alongside TypeScript for auto-detected polyfills? Yes
? Use history mode for router? (Requires proper server setup for index fallback in production) Yes
? Pick a CSS pre-processor (PostCSS, Autoprefixer and CSS Modules are supported by default): Sass/SCSS (with node-sass)
? Pick a linter / formatter config: 
  TSLint
  ESLint with error prevention only 
  ESLint + Airbnb config
  ESLint + Standard config
> ESLint + Prettier

配置保存自動修復(fù)eslint錯誤

在沒有做任何配置時右遭,此時鹤耍,如果出現(xiàn)不符合eslint規(guī)則的代碼刚盈,會出現(xiàn)以下1 error potentially fixable with the '--fix' option.報錯:

 error  in ./src/main.ts

Module Error (from ./node_modules/eslint-loader/index.js):
error: Replace `h` with `(h)` (prettier/prettier) at src\main.ts:19:11:
  17 |   router,
  18 |   store,
> 19 |   render: h => h(App)
     |           ^
  20 | }).$mount("#app");
  21 |


1 error found.
1 error potentially fixable with the `--fix` option.

 @ multi (webpack)-dev-server/client?http://10.21.27.126:8080/sockjs-node (webpack)/hot/dev-server.js ./src/main.ts

因此需要在eslint配置上增加--fix選項:
在項目根目錄增加vue.config.js

//vue.config.js
module.exports = {
  chainWebpack: config => {
    config.module
      .rule("eslint")
      .use("eslint-loader")
      .loader("eslint-loader")
      .tap(options => {
        options.fix = true;
        return options;
      });
  }
};

然后重啟服務(wù),即執(zhí)行npm run serve,此時就可以保存自動修復(fù)eslint問題了诀豁。

配置保存自動格式化

我們安裝了prettier插件畔规,但是保存時代碼并沒有自動格式化伏穆,因為我們沒有對編輯器vscode進行配置拘泞。

配置eslint啟用prettier

在根目錄的.eslintrc.js中,在extends數(shù)組中增加plugin:prettier/recommended枕扫,這將在ESLint中啟用Prettier支持:

//.eslintrc.js
module.exports = {
  root: true,
  env: {
    node: true
  },
  extends: [
    "plugin:vue/essential",
    "@vue/prettier",
    "@vue/typescript",
    "plugin:prettier/recommended" // add prettier-eslint plugin which will uses the `.prettierrc.js` config
  ],
  rules: {
    //'prettier/prettier': 'error',
    "no-console": process.env.NODE_ENV === "production" ? "error" : "off",
    "no-debugger": process.env.NODE_ENV === "production" ? "error" : "off"
  },
  parserOptions: {
    parser: "@typescript-eslint/parser"
  },
  overrides: [
    {
      files: ["**/__tests__/*.{j,t}s?(x)"],
      env: {
        mocha: true
      }
    }
  ]
};

在根目錄新建.prettierrc.js陪腌,定義項目格式化代碼的規(guī)則,比如:

//.prettierrc.js
module.exports = {
    printWidth: 120,
    tabWidth: 2,
    tabs: false,
    semi: true,
    singleQuote: false,
    quoteProps: 'as-needed',
    tailingComma: 'all',
    bracketSpacing: true,
    jsxBracketSameLine: true,
    arrowParens: 'always',
    htmlWhitespaceSensitivity: 'ignore',
};

配置vscode保存啟動eslint、prettier

打開vscode偷厦,鍵盤ctrl+shift+p商叹,輸入setting,選擇Open User Settings

image.png

打開編輯器設(shè)置后只泼,在Extensions中找到ESLint勾選以下三項

  1. Auto Fix On Save

  2. Enable

  3. Lint Task: Enable


    image.png

找到Validate點擊Edit in settings.json

image.png

打開配置文件,編輯如下:

{
    "window.zoomLevel": 0,
    "terminal.integrated.rendererType": "dom",
    "eslint.autoFixOnSave": true,
    "editor.formatOnSave": true,
    "eslint.validate": [
        {
            "language": "vue",
            "autoFix": true
        },
        {
            "language": "html",
            "autoFix": true
        },
        {
            "language": "javascript",
            "autoFix": true
        }
    ],
    "eslint.lintTask.enable": true,
}

到底卵洗,基本完成请唱,我們就可以保存自動格式化代碼了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末过蹂,一起剝皮案震驚了整個濱河市十绑,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌酷勺,老刑警劉巖本橙,帶你破解...
    沈念sama閱讀 218,755評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異脆诉,居然都是意外死亡甚亭,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,305評論 3 395
  • 文/潘曉璐 我一進店門击胜,熙熙樓的掌柜王于貴愁眉苦臉地迎上來亏狰,“玉大人,你說我怎么就攤上這事偶摔∠就伲” “怎么了?”我有些...
    開封第一講書人閱讀 165,138評論 0 355
  • 文/不壞的土叔 我叫張陵辰斋,是天一觀的道長策州。 經(jīng)常有香客問我,道長宫仗,這世上最難降的妖魔是什么够挂? 我笑而不...
    開封第一講書人閱讀 58,791評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮锰什,結(jié)果婚禮上下硕,老公的妹妹穿的比我還像新娘。我一直安慰自己汁胆,他們只是感情好梭姓,可當(dāng)我...
    茶點故事閱讀 67,794評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著嫩码,像睡著了一般誉尖。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上铸题,一...
    開封第一講書人閱讀 51,631評論 1 305
  • 那天铡恕,我揣著相機與錄音琢感,去河邊找鬼。 笑死探熔,一個胖子當(dāng)著我的面吹牛驹针,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播诀艰,決...
    沈念sama閱讀 40,362評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼柬甥,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了其垄?” 一聲冷哼從身側(cè)響起苛蒲,我...
    開封第一講書人閱讀 39,264評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎绿满,沒想到半個月后臂外,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,724評論 1 315
  • 正文 獨居荒郊野嶺守林人離奇死亡喇颁,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,900評論 3 336
  • 正文 我和宋清朗相戀三年漏健,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片无牵。...
    茶點故事閱讀 40,040評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡漾肮,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出茎毁,到底是詐尸還是另有隱情克懊,我是刑警寧澤,帶...
    沈念sama閱讀 35,742評論 5 346
  • 正文 年R本政府宣布七蜘,位于F島的核電站谭溉,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏橡卤。R本人自食惡果不足惜扮念,卻給世界環(huán)境...
    茶點故事閱讀 41,364評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望碧库。 院中可真熱鬧柜与,春花似錦、人聲如沸嵌灰。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,944評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽沽瞭。三九已至迁匠,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背城丧。 一陣腳步聲響...
    開封第一講書人閱讀 33,060評論 1 270
  • 我被黑心中介騙來泰國打工延曙, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人亡哄。 一個月前我還...
    沈念sama閱讀 48,247評論 3 371
  • 正文 我出身青樓枝缔,卻偏偏與公主長得像,于是被迫代替她去往敵國和親蚊惯。 傳聞我的和親對象是個殘疾皇子魂仍,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,979評論 2 355