設定 ESLint + Prettier
tags: 環境設定
category: Front-End
description: 設定 ESLint + Prettier
created_at: 2022/01/23 10:30:00
前言
這裡假設使用 VSCode
+ React
當範例
事前準備
- 裝好
Node.js
先建立好 React 專案
$ npx create-react-app my-app
把 ESLint 初始化
$ npx eslint --init
或是 Global
安裝後執行
$ npm i -g eslint
$ eslint --init
然後他會問你一些問題,然後幫你設定好,這邊假設我希望
- 幫我檢查語法、找問題、幫我修復 code style
- 我的專案使用
import
、export
- 我的專案跑在
React
- 我沒有使用
TypeScript
- 我的程式只跑在瀏覽器
- 直接使用 Standard 標準
- 設定檔使用
Json
然後他問完最後會問你要不要用 npm
幫你裝那些套件。
? How would you like to use ESLint? ...
To check syntax only
To check syntax and find problems
> To check syntax, find problems, and enforce code style
? What type of modules does your project use? ...
> JavaScript modules (import/export)
CommonJS (require/exports)
None of these
? Which framework does your project use? ...
> React
Vue.js
None of these
? Does your project use TypeScript? » No / Yes
? Where does your code run? ... (Press <space> to select, <a> to toggle all, <i> to invert selection)
√ Browser
Node
? How would you like to define a style for your project? ...
> Use a popular style guide
Answer questions about your style
? Which style guide do you want to follow? ...
Airbnb: https://github.com/airbnb/javascript
> Standard: https://github.com/standard/standard
Google: https://github.com/google/eslint-config-google
XO: https://github.com/xojs/eslint-config-xo
? What format do you want your config file to be in? ...
JavaScript
YAML
> JSON
? The style guide "standard" requires eslint@^7.12.1. You are currently using [email protected].
Do you want to downgrade? » No / Yes
eslint-plugin-react@latest eslint-config-standard@latest eslint@^7.12.1 eslint-plugin-import@^2.22.1 eslint-plugin-node@^11.1.0 eslint-plugin-promise@^4.2.1 || ^5.0.0
? Would you like to install them now with npm? » No / Yes
安裝 VSCode ESLint 擴充功能
設定 VSCode 設定
加上下面這一段
{
// ...
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
}
// ...
}
再來只要按下存檔 Ctrl + S
就會幫你修復了。
安裝 Prettier
$ npm i -D prettier eslint-plugin-prettier eslint-config-prettier
新增設定檔 .prettierrc.json
{
"trailingComma": "es5",
"tabWidth": 2,
"semi": false,
"singleQuote": true
}
設定 .eslintrc.json
{
// ...
"extends": [
// ...
"prettier"
],
"plugins": [
// ...
"prettier"
],
"rules": {
// ...
"prettier/prettier": "error"
}
}
解決紅紅的 Error
在設定好 ESLint
後,會發現噴了一堆紅字,有兩個解法,一個是關掉 ESLint
的 rules
, 一個是乖乖地去 Import React
。
- 補上
rules
{
// ...
"rules": {
// ...
"react/react-in-jsx-scope": false
}
}
- 到每一個
jsx
上面補上
import React from 'react'
但是每次這樣打其實滿累的,而且 VSCode
預設以為每一個 JavaScript
檔案都是獨立的,所以沒有辦法幫你 Import
,這時可以加上一個 jsconfig.json
檔案。
{
"compilerOptions": {
"checkJs": true,
"baseUrl": "./src",
"jsx": "react"
}
}
這時只要到你有紅紅的地方,點下 Quick Fix
就會可以讓你 Import
了
最後更新時間: 2022年01月23日.