Thiết lập Development Environment
Hướng dẫn hoàn chỉnh cho việc thiết lập một development environment để contribute vào LegoCity.
Tổng quan
Hướng dẫn này dành cho developers muốn:
- 🛠️ Xây dựng features mới
- 🐛 Sửa bugs và issues
- 🧪 Viết và chạy tests
- 📦 Tạo custom blocks và plugins
- 🔍 Debug và profile code
Điều kiện Tiên quyết
Công cụ Bắt buộc
Cài đặt những công cụ này trước khi tiếp tục:
Node.js & pnpm:
# Kiểm tra phiên bản Node.js (cần 18.x hoặc 20.x)
node --version
# Cài đặt pnpm globally
npm install -g pnpm
# Xác minh pnpm
pnpm --versionGit:
# Kiểm tra cài đặt Git
git --version
# Cấu hình Git
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"MongoDB:
Option 1: Cài đặt Local
# Windows (qua Chocolatey)
choco install mongodb
# macOS (qua Homebrew)
brew install mongodb-community
# Linux (Ubuntu/Debian)
sudo apt install mongodbOption 2: Docker
docker run -d -p 27017:27017 --name mongodb mongo:6VS Code (Được khuyến nghị):
Cài đặt Visual Studio Code với extensions:
- ESLint
- Prettier
- TypeScript and JavaScript Language Features
- Tailwind CSS IntelliSense
- MongoDB for VS Code
Công cụ Tùy chọn
Nâng cao trải nghiệm development của bạn:
- Docker Desktop - Cho containerized services
- Postman hoặc Insomnia - API testing
- MongoDB Compass - Database GUI
- Redux DevTools - State debugging
Thiết lập Ban đầu
1. Fork & Clone Repository
# Fork trên GitHub trước, sau đó:
git clone https://github.com/YOUR_USERNAME/LegoCity.git
cd LegoCity
# Thêm upstream remote
git remote add upstream https://github.com/CTU-SematX/LegoCity.git
# Xác minh remotes
git remote -v2. Cài đặt Dependencies
cd dashboard
pnpm installĐiều này cài đặt:
- Next.js framework
- PayloadCMS và plugins
- React và UI libraries
- Development tools
3. Thiết lập Environment
# Copy example env file
cp .env.example .envChỉnh sửa .env với development settings:
# Database
DATABASE_URI=mongodb://127.0.0.1/legocity-dev
# Security (tạo với: openssl rand -hex 32)
PAYLOAD_SECRET=dev-secret-min-32-characters-long-replace-in-production
# Server
NEXT_PUBLIC_SERVER_URL=http://localhost:3000
# Mapbox (lấy token từ mapbox.com)
NEXT_PUBLIC_MAPBOX_TOKEN=pk.your_mapbox_token
# NGSI-LD Context Broker (nếu chạy locally)
NGSI_LD_BROKER_URL=http://localhost:1026
# Development
NODE_ENV=development4. Khởi động Development Server
# Khởi động với hot reload
pnpm dev
# Hoặc với turbopack (nhanh hơn)
pnpm dev --turboTruy cập tại:
- Frontend: http://localhost:3000
- Admin: http://localhost:3000/admin
- API: http://localhost:3000/api
5. Tạo Admin Account
Khi lần đầu truy cập /admin, bạn sẽ tạo user đầu tiên:
Email: dev@example.com
Password: [chọn password mạnh]Development Workflow
Branch Strategy
# Luôn bắt đầu từ main mới nhất
git checkout main
git pull upstream main
# Tạo feature branch
git checkout -b feature/your-feature-name
# Hoặc bug fix branch
git checkout -b fix/issue-123Thực hiện Thay đổi
- Edit Code - Thực hiện thay đổi trong
dashboard/src/ - Hot Reload - Thay đổi xuất hiện tự động
- Check Console - Theo dõi errors
- Test Changes - Xác minh functionality hoạt động
Code Style
LegoCity sử dụng ESLint và Prettier:
# Kiểm tra linting
pnpm lint
# Tự động sửa issues
pnpm lint:fix
# Format code
pnpm formatType Checking
# Kiểm tra TypeScript types
pnpm type-check
# Build để xác minh không có errors
pnpm buildCấu trúc Project
dashboard/
├── src/
│ ├── app/ # Next.js App Router
│ │ ├── (frontend)/ # Public pages
│ │ └── (payload)/ # Admin routes
│ ├── blocks/ # PayloadCMS blocks
│ ├── collections/ # Content types
│ ├── components/ # React components
│ ├── fields/ # Custom fields
│ ├── hooks/ # React hooks
│ ├── plugins/ # PayloadCMS plugins
│ ├── providers/ # Context providers
│ └── utilities/ # Helper functions
├── public/ # Static assets
├── payload.config.ts # Cấu hình CMS
└── next.config.js # Cấu hình Next.jsDevelopment Tasks
Thêm một Block Mới
Tạo block directory:
bashmkdir -p src/blocks/MyBlockTạo config:
typescript// src/blocks/MyBlock/config.ts import { Block } from "payload/types"; export const MyBlock: Block = { slug: "myBlock", fields: [ { name: "title", type: "text", required: true, }, ], };Tạo component:
tsx// src/blocks/MyBlock/Component.tsx export const MyBlockComponent = ({ title }) => <div>{title}</div>;Đăng ký trong
RenderBlocks.tsx
Xem Creating Blocks Guide cho chi tiết.
Tạo một Collection
// src/collections/MyCollection.ts
import { CollectionConfig } from "payload/types";
export const MyCollection: CollectionConfig = {
slug: "my-collection",
admin: {
useAsTitle: "name",
},
fields: [
{
name: "name",
type: "text",
required: true,
},
],
};Đăng ký trong payload.config.ts:
collections: [
// ... existing
MyCollection,
],Viết Tests
# Chạy tất cả tests
pnpm test
# Chạy specific test
pnpm test blocks
# Watch mode
pnpm test:watch
# Coverage report
pnpm test:coverageExample test:
// src/blocks/MyBlock/MyBlock.test.ts
import { render } from "@testing-library/react";
import { MyBlockComponent } from "./Component";
describe("MyBlock", () => {
it("renders title", () => {
const { getByText } = render(<MyBlockComponent title="Test" />);
expect(getByText("Test")).toBeInTheDocument();
});
});Debugging
VS Code Debug Configuration
Tạo .vscode/launch.json:
{
"version": "0.2.0",
"configurations": [
{
"name": "Next.js: debug server-side",
"type": "node-terminal",
"request": "launch",
"command": "pnpm dev"
},
{
"name": "Next.js: debug client-side",
"type": "chrome",
"request": "launch",
"url": "http://localhost:3000"
}
]
}Browser DevTools
- React DevTools - Inspect component tree
- Network Tab - Debug API calls
- Console - Xem logs và errors
Logging
// Development logging
if (process.env.NODE_ENV === "development") {
console.log("Debug info:", data);
}
// PayloadCMS logging
payload.logger.info("Info message");
payload.logger.error("Error message");Làm việc với MongoDB
MongoDB Compass
Kết nối tới: mongodb://127.0.0.1:27017/legocity-dev
Xem và chỉnh sửa:
- Collections (Pages, Posts, Media, v.v.)
- Documents
- Indexes
Command Line
# Kết nối tới database
mongosh legocity-dev
# Liệt kê collections
show collections
# Tìm documents
db.pages.find().pretty()
# Xóa collection
db.pages.deleteMany({})Seed Data
# Load sample data
pnpm seed
# Custom seed script
pnpm seed:customBuilding & Testing
Development Build
# Build cho development
pnpm build
# Khởi động production server
pnpm startProduction Build
# Build tối ưu cho production
NODE_ENV=production pnpm build
# Phân tích bundle size
pnpm build --analyzeQuality Checks
# Chạy tất cả checks trước khi commit
pnpm lint # ESLint
pnpm type-check # TypeScript
pnpm test # Jest tests
pnpm build # Production buildGit Workflow
Commit Changes
# Stage changes
git add .
# Commit với descriptive message
git commit -m "feat: add new block component"
# Tuân theo conventional commits:
# feat: feature mới
# fix: sửa bug
# docs: tài liệu
# style: formatting
# refactor: cấu trúc lại code
# test: thêm tests
# chore: maintenancePush & Tạo PR
# Push lên fork của bạn
git push origin feature/your-feature
# Tạo Pull Request trên GitHub
# Điền PR template
# Đợi reviewGiữ Fork Updated
# Fetch upstream changes
git fetch upstream
# Cập nhật main branch
git checkout main
git merge upstream/main
git push origin main
# Rebase feature branch
git checkout feature/your-feature
git rebase mainCommon Issues
Port 3000 Đã được Sử dụng
# Kill process
npx kill-port 3000
# Hoặc sử dụng port khác
PORT=3001 pnpm devBuild Errors
# Xóa cache
rm -rf .next node_modules
pnpm install
pnpm devMongoDB Connection Issues
# Kiểm tra MongoDB đang chạy
mongosh --eval "db.version()"
# Khởi động lại MongoDB
# Windows: net restart MongoDB
# Linux: sudo systemctl restart mongodType Errors
# Tạo lại Payload types
pnpm payload generate:types
# Kiểm tra tsconfig.json pathsBest Practices
Code Quality
✅ Viết TypeScript, tránh any
✅ Tuân theo ESLint rules
✅ Viết tests cho features mới
✅ Document logic phức tạp
Performance
✅ Sử dụng React Server Components khi có thể
✅ Tối ưu images với next/image
✅ Lazy load heavy components
✅ Monitor bundle size
Security
✅ Không bao giờ commit secrets
✅ Validate user inputs
✅ Sử dụng environment variables
✅ Giữ dependencies updated
Git
✅ Viết commit messages rõ ràng
✅ Giữ PRs focused và nhỏ
✅ Rebase trước khi push
✅ Review PR của chính bạn trước
Resources
Getting Help
- 💬 GitHub Discussions
- 🐛 Report Issues
- 📧 Email: CTU-SematX Team
Environment sẵn sàng? Bắt đầu xây dựng với Development Guide.