Dark mode
dprint
dprint คือเครื่องมือจัดรูปแบบโค้ดที่เขียนด้วย Rust เน้นความเร็วและความเสถียร รองรับหลายภาษาเช่น JavaScript, TypeScript, JSON, Markdown และอื่นๆ
การติดตั้ง
ขั้นตอนการติดตั้ง dprint
- ติดตั้งผ่าน npm:
bash
npm install --save-dev dprint
- สร้างไฟล์
dprint.json
:
json
{
"typescript": {
"indentWidth": 2,
"lineWidth": 80,
"semiColons": "always",
"quoteStyle": "alwaysSingle",
"trailingCommas": "always"
},
"json": {
"indentWidth": 2,
"lineWidth": 80
},
"markdown": {
"lineWidth": 80,
"textWrap": "always"
},
"includes": ["**/*.{ts,tsx,js,jsx,json,md}"],
"excludes": ["**/node_modules", "**/*-lock.json"],
"plugins": ["typescript", "json", "markdown"]
}
การใช้งานพื้นฐาน
คำสั่งพื้นฐานของ dprint
bash
# ตรวจสอบการจัดรูปแบบ
npx dprint check
# จัดรูปแบบไฟล์ทั้งหมด
npx dprint fmt
# ตรวจสอบไฟล์เฉพาะ
npx dprint check src/file.ts
# จัดรูปแบบไฟล์เฉพาะ
npx dprint fmt src/file.ts
การตั้งค่า
การกำหนดค่าใน dprint.json
json
{
"typescript": {
"indentWidth": 2,
"lineWidth": 80,
"semiColons": "always",
"quoteStyle": "alwaysSingle",
"trailingCommas": "always",
"bracePosition": "sameLineUnlessHanging",
"singleBodyPosition": "sameLine",
"preferHanging": true,
"preferSingleLine": false,
"operatorPosition": "sameLine",
"commentLine": {
"forceSpaceAfterSlashes": true
}
},
"json": {
"indentWidth": 2,
"lineWidth": 80
},
"markdown": {
"lineWidth": 80,
"textWrap": "always",
"emphasisKind": "asterisks"
}
}
การใช้งานกับ VSCode
การตั้งค่า VSCode Extension
- ติดตั้ง dprint extension
- เพิ่มการตั้งค่าใน
settings.json
:
json
{
"editor.formatOnSave": true,
"[typescript]": {
"editor.defaultFormatter": "dprint.dprint"
},
"[javascript]": {
"editor.defaultFormatter": "dprint.dprint"
},
"[json]": {
"editor.defaultFormatter": "dprint.dprint"
},
"[markdown]": {
"editor.defaultFormatter": "dprint.dprint"
}
}
การใช้งานกับ CI/CD
ตัวอย่างการใช้งานใน GitHub Actions
yaml
name: Format Check
on: [push, pull_request]
jobs:
format:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '18'
- run: npm install
- name: Check Format
run: npx dprint check
คำแนะนำ
TIP
- ใช้ร่วมกับ ESLint สำหรับการตรวจสอบคุณภาพโค้ด
- ตั้งค่า format on save ใน VSCode
- กำหนด includes และ excludes ให้เหมาะสม
- อัพเดท dprint และ plugins เป็นเวอร์ชันล่าสุดเสมอ
ข้อควรระวัง
WARNING
- ตรวจสอบการตั้งค่าที่อาจขัดแย้งกับ Prettier หรือ formatter อื่น
- ระวังการจัดรูปแบบไฟล์ที่ยังไม่ได้ commit
- สำรองโค้ดก่อนจัดรูปแบบครั้งแรก
- ตรวจสอบ performance เมื่อใช้กับโปรเจคขนาดใหญ่