ใช้ ESLint กับ Prettier ในการ auto format typescript code เพื่อชีวิตที่ดีขึ้น
วันนี้ผมขอนำเสนอวิธีการ setup prettier กับ ESLint บน vscode ที่ช่วยทำ auto format เมื่อเรา save ไฟล์
ผมจะใช้โปรเจคที่เขียนด้วย Node.js และใช้ภาษา TypeScript ในตัวอย่างนี้ครับ
1. เริ่มจากการสร้าง typescript nodejs project โดยการรันคำสั่งด้านล่างใน folder ว่างที่เราสร้างขึ้นมา
npm init
npm install -D typescript ts-node @types/node
npx tsc — init
2. สร้างไฟล์ src/index.ts โดยมีโค้ดง่ายๆ ตามด้านล่าง แล้วก็ทดสอบรัน npx ts-node src/index.ts
3.หลังจากเรา setup typescript nodejs project เรียบร้อยแล้ว เราจะมาติดตั้ง ESLint, Prettier และ plugin ที่เกี่ยวข้อง โดยการรันคำสั่งด้านล่างนี้ครับ
npm install — save-dev eslint prettier prettier-eslint eslint-config-prettier eslint-plugin-prettier @typescript-eslint/parser @typescript-eslint/eslint-plugin
4. สร้าง config file ให้กับ ESLint โดยการสร้างไฟล์ .eslintrc.js ใน root ของ project folder
5. สร้าง config file ให้กับ Prettier โดยการสร้างไฟล์ชื่อ .prettierrc.js ใน root ของ project folder
6. ติดตั้ง vscode extension 2 ตัวนี้ครับ
https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslin
thttps://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode
7. เราจะเห็น extension เริ่มทำงาน โดยการขีดเส้นแดงตรงโค้ดที่ไม่ตรงตาม rule
8. ตอนนี้เราสามารถ manual fix ตามจุดที่ไม่ตรงกับ rule ได้
9.ทีนี้เราจะมา config vs code ให้ auto format ตอน save file โดยการสร้างไฟล์ .vscode/setting.json
10. ถึงตอนนี้ทุกครั้งที่เรา save file vscode จะ auto format โค้ด ให้เรา
11. สุดท้ายนี้ ผมมี project ที่ setup ตาม step ด้านบนไว้แล้ว อยู่ที่ https://github.com/flowaccount/demo-eslint-prettier เพื่อนๆ สามารถ clone ไปลองเล่นกันได้เลยครับ
ข้อมูลอ้างอิงจาก
Prettier · Opinionated Code Formatter
Opinionated Code Formatter
Opinionated Code Formatterprettier.io
หากชอบบทความของ FlowAccount Tech Blog อย่าลืมกด Follow นะครับ ติดตามบทความอื่นจาก FlowAccount Tech Blog ได้ที่ https://medium.com/flowaccount-tech
Open Positions jobs available on FlowAccount > https://flowaccount.com/en/jobs