vita shela
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
Invitee
Publish Note

Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

Your note will be visible on your profile and discoverable by anyone.
Your note is now live.
This note is visible on your profile and discoverable online.
Everyone on the web can find and read all notes of this public team.
See published notes
Unpublish note
Please check the box to agree to the Community Guidelines.
View profile
Engagement control
Commenting
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
  • Everyone
Suggest edit
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
Emoji Reply
Enable
Import from Dropbox Google Drive Gist Clipboard
   owned this note    owned this note      
Published Linked with GitHub
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
# Day 9 | 如何在 React 專案設置 ESLint 和 Prettier ## 本節大綱 - 前言 - 如何在 React 專案設置 ESLint 和 Prettier - 在App.test.js 檔案中,會顯示 'test' is not defined 的錯誤 - 參考資料 - 結論 ## 前言 這裡是要分享在建立 React 的專案之前,我的第一步一定就是,先安裝 ESLint 和 Prettier 這兩個套件。 利用 ESLint 針對 JavaScript、React 語法的檢查跟 Prettier 對程式碼的格式化,這樣的好處是,可以檢查自己的程式碼是否有撰寫錯誤,對團隊而言,整個團隊程式碼的撰寫風格將會一致,塑造團隊的風格。 ## 如何在 React 專案設置 ESLint 和 Prettier ### ESLint 介紹 ESLint 是一個開源的專案,可以幫助您尋找和修正程式碼中的問題。無論您的程式碼是要在瀏覽器還是伺服器執行,又或者是否有使用框架,ESLint 都可以幫助您的程式碼擁有良好的規範。 #### ESLint 安裝說明 本人喜好使用 Yarn 工具,故後續都會使用 Yarn 來做示範。 - 使用 Create React App (CRA) 建立專案,可依個人喜好,選擇 `npx`、`npm` 或 `Yarn`。至於 CRA 是什麼,後續會再做介紹。 `npx create-react-app my-app` `npm init react-app my-app` `yarn create react-app my-app` - 安裝 ESLint 套件:`yarn add -D eslint` - 執行 ESLint 初始化:`yarn eslint --init` 以下是在初始化的過程中,會出現以下的詢問選項整理。 ```shell // 請選擇第二項,選擇第三項就會有 Airbnb、Google 等規範,要我們選擇。 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 ``` ```shell // 請選擇第一項。 What type of modules does your project use? ❯ JavaScript modules (import/export) CommonJS (require/exports) None of these ``` ```shell // 因為是以 React 做示範,故請選擇 React。 Which framework does your project use? ❯ React Vue.js None of these ``` ```shell // 依照專案來決定是否要使用 TypeScript。 Does your project use TypeScript? › No / Yes ``` ```shell // 因為 React 是執行在瀏覽器上,故請選擇 Browser。 Where does your code run? ✔ Browser Node ``` ```shell // 依個人喜好做選擇,我都選擇 JSON。 What format do you want your config file to be in? JavaScript YAML ❯ JSON ``` ```shell // 這裡會詢問是否要透過 npm 來安裝 eslint-plugin-react@latest。 // 請選擇 No,因為統一使用 yarn 來安裝。 Would you like to install them now with npm? › No / Yes ``` - 初始化結束之後,執行此指令:`yarn add -D eslint-plugin-react@latest` ### Prettier 介紹 Prettier 是一個可以針對程式碼的格式執行排版、對齊及格式化的擴充套件,可設定為存檔時自動格式化,不用再浪費時間手動格式化程式碼。同時也能夠統一團隊程式碼風格,並且可以根據團隊規範,去調整相關設定規則。 #### Prettier 安裝說明 - 安裝 Prettier 套件:`yarn add --dev --exact prettier` - 安裝 `eslint-config-prettier` 套件,其目的為關閉所有不必要或可能 ESLint 與 Prettier 衝突的規則。 `yarn add -D eslint-config-prettier` - 新增 `"prettier"` 到 `"extends"` 的陣列裡在您的 `.eslintrc.*` 檔案 (這裡是 `.eslintrc.json`),並且要放在最後一個位置,來覆蓋其他配置(官網說明)。 ```json // 要把 prettier 放在最後面。 { "extends": [ // ..., "prettier" ] } ``` - 安裝 `eslint-plugin-prettier` 套件,將 Prettier 作為 ESLint 規則運行,並將差異報告為單個 ESLint 問題。 `yarn add -D eslint-plugin-prettier` - 在 `.eslintrc.json` 檔案調整 ESLint 與 Prettier的警告顯示。 ```json // ESLint 預設警告是紅色 (danger) 顯示。 // Prettier 預設警告也是紅色 (danger) 顯示,不跟 ESLint 混淆,因此改成黃色 (warning) 顯示。 { "plugins": ["prettier"], "rules": { "prettier/prettier": "warn" } } ``` - 在 `.eslintrc.json` 檔案,新增 `plugin:prettier/recommended` 設定。 ```json { ..., "extends": ["plugin:prettier/recommended"] } ``` - 在您的專案目錄,新增 `.prettierrc.*` (本人喜好是 `.prettierrc.json`) 設定檔案,並加上以下格式化的規則。 > 另外補充說明一點,有些人的 Prettier 配置,會把預設值也寫進去,這時候您會心想,預設值顧名思義就是您不去寫它,這些規則的規範就是已經訂好了,又何必還去把這預設的規則寫出來,經跟資深前輩的詢問啊,二個思考的方向可以去想,第一個您還真的就不用寫,第二個是就是怕官方,突然去改掉這個預設值,屆時整個程式碼的風格就會跑掉,故這點想法。分享給您。 ```json // 其中 jsxSingleQuote,這是指在 jsx 裡也是使用單引號規則。 { "printWidth": 100, "useTabs": true, "singleQuote": true, "jsxSingleQuote": true, "trailingComma": "all" } ``` - 在您的專案目錄,新增 `.prettierignore` 排除檔案,並加上以下要排除格式化的目錄。 ```yaml .github .husky dist node_modules ``` - 在 `package.json` 檔案新增 prettier and lint 檢查及格式化指令。 ```json "scripts": { ..., // ..., // ESLint 檢查指令 "lint:check": "eslint --ext=js,jsx src/", // ESLint 修正指令,--fix 修正,--ext=.js,.jsx 修正副檔名為 .js,.jsx,src/ 底下全部目錄 "lint": "eslint --fix --ext=js,jsx src/", // prettier 檢查指令 "format:check": "prettier . --check --ignore-unknown", // prettier 格式化指令,. 是全部目錄,--write 是複寫,--ignore-unknown 略過它不認識的檔案 "format": "prettier . --write --ignore-unknown", } ``` ## 在App.test.js 檔案中,會顯示 'test' is not defined 的錯誤 要處理的是在 App.test.js 檔案的錯誤。 ![App.test.js Error](https://i.imgur.com/My3NPZL.png) 很明顯是 testing-library 套件的問題,但是其實要安裝 jest 套件,這個問題才會解決掉。 `yarn add -D eslint-plugin-jest` 按照官網解說,需在 `.eslintrc.json` 加上以下: ```json { "plugins": ["jest"] } ``` 最重要的一步,通過以下方式告訴 ESLint Jest 提供的環境變數: ```json { "env": { "jest/globals": true } } ``` ## 參考資料 - [ESLint](https://eslint.org/) - [Prettier](https://prettier.io/) - [eslint-plugin-jest](https://www.npmjs.com/package/eslint-plugin-jest) - [Create React App with ESLint & Prettier in VSCode (2022)](https://www.youtube.com/watch?v=xinJSYiOB6Q) - [Setup ESLINT and PRETTIER in React app](https://dev.to/knowankit/setup-eslint-and-prettier-in-react-app-357b) ## 結論 透過這篇文章教學,一步一步地告訴您,在寫任何 React 的專案時,要怎麼使用 ESLint 與 Prettier 一起搭配使用又不會互相衝突的教學。 這裡最後再補充一點,曾經也試過上面的教學,但是,都發現管不是 ESLint 或 Prettier 都不會有任何作用,後來發現我的 VS Code 軟體重開就好。 針對此問題,最近問過一些資深前輩,他們的回覆是,正常來講應該是不需要重開的,意思就是馬上改 ESLint 或 Prettier 的配置,VS Code 應該就會馬上有反應這樣,哪這個問題頗羅生門的,歡迎在觀看這篇文章的您,也有碰到或者知道原因在哪裡,也請告訴我,感謝您。 ###### tags:`(整理) 2022 鐵人賽`

Import from clipboard

Paste your markdown or webpage here...

Advanced permission required

Your current role can only read. Ask the system administrator to acquire write and comment permission.

This team is disabled

Sorry, this team is disabled. You can't edit this note.

This note is locked

Sorry, only owner can edit this note.

Reach the limit

Sorry, you've reached the max length this note can be.
Please reduce the content or divide it to more notes, thank you!

Import from Gist

Import from Snippet

or

Export to Snippet

Are you sure?

Do you really want to delete this note?
All users will lose their connection.

Create a note from template

Create a note from template

Oops...
This template has been removed or transferred.
Upgrade
All
  • All
  • Team
No template.

Create a template

Upgrade

Delete template

Do you really want to delete this template?
Turn this template into a regular note and keep its content, versions, and comments.

This page need refresh

You have an incompatible client version.
Refresh to update.
New version available!
See releases notes here
Refresh to enjoy new features.
Your user state has changed.
Refresh to load new user state.

Sign in

Forgot password

or

By clicking below, you agree to our terms of service.

Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
Wallet ( )
Connect another wallet

New to HackMD? Sign up

Help

  • English
  • 中文
  • Français
  • Deutsch
  • 日本語
  • Español
  • Català
  • Ελληνικά
  • Português
  • italiano
  • Türkçe
  • Русский
  • Nederlands
  • hrvatski jezik
  • język polski
  • Українська
  • हिन्दी
  • svenska
  • Esperanto
  • dansk

Documents

Help & Tutorial

How to use Book mode

Slide Example

API Docs

Edit in VSCode

Install browser extension

Contacts

Feedback

Discord

Send us email

Resources

Releases

Pricing

Blog

Policy

Terms

Privacy

Cheatsheet

Syntax Example Reference
# Header Header 基本排版
- Unordered List
  • Unordered List
1. Ordered List
  1. Ordered List
- [ ] Todo List
  • Todo List
> Blockquote
Blockquote
**Bold font** Bold font
*Italics font* Italics font
~~Strikethrough~~ Strikethrough
19^th^ 19th
H~2~O H2O
++Inserted text++ Inserted text
==Marked text== Marked text
[link text](https:// "title") Link
![image alt](https:// "title") Image
`Code` Code 在筆記中貼入程式碼
```javascript
var i = 0;
```
var i = 0;
:smile: :smile: Emoji list
{%youtube youtube_id %} Externals
$L^aT_eX$ LaTeX
:::info
This is a alert area.
:::

This is a alert area.

Versions and GitHub Sync
Get Full History Access

  • Edit version name
  • Delete

revision author avatar     named on  

More Less

Note content is identical to the latest version.
Compare
    Choose a version
    No search result
    Version not found
Sign in to link this note to GitHub
Learn more
This note is not linked with GitHub
 

Feedback

Submission failed, please try again

Thanks for your support.

On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

Please give us some advice and help us improve HackMD.

 

Thanks for your feedback

Remove version name

Do you want to remove this version name and description?

Transfer ownership

Transfer to
    Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

      Link with GitHub

      Please authorize HackMD on GitHub
      • Please sign in to GitHub and install the HackMD app on your GitHub repo.
      • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
      Learn more  Sign in to GitHub

      Push the note to GitHub Push to GitHub Pull a file from GitHub

        Authorize again
       

      Choose which file to push to

      Select repo
      Refresh Authorize more repos
      Select branch
      Select file
      Select branch
      Choose version(s) to push
      • Save a new version and push
      • Choose from existing versions
      Include title and tags
      Available push count

      Pull from GitHub

       
      File from GitHub
      File from HackMD

      GitHub Link Settings

      File linked

      Linked by
      File path
      Last synced branch
      Available push count

      Danger Zone

      Unlink
      You will no longer receive notification when GitHub file changes after unlink.

      Syncing

      Push failed

      Push successfully