Monorepo React + TypeScript + Ant Design

admin . 10:32 am
Dưới đây là Tutorial chi tiết từ đầu để tạo một dự án Monorepo sử dụng React + TypeScript + Ant Design, phù hợp để dùng nhiều app hoặc chia sẻ UI component giữa các module.
✅ Bước 1: Khởi tạo workspace
mkdir my-monorepo && cd my-monorepo
yarn init -y
Cấu hình Yarn Workspaces trong package.json
:
{
"name": "my-monorepo",
"private": true,
"workspaces": ["apps/*", "packages/*"],
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"antd": "^5.0.0"
},
"resolutions": {
"react": "^18.2.0",
"react-dom": "^18.2.0"
}
}
✅ Bước 2: Cấu hình TypeScript dùng chung
Tạo file tsconfig.base.json
tại root:
{
"compilerOptions": {
"target": "ES6",
"module": "ESNext",
"lib": ["DOM", "ESNext"],
"jsx": "react-jsx",
"moduleResolution": "node",
"esModuleInterop": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"baseUrl": ".",
"paths": {
"@myorg/ui": ["packages/ui/src"]
}
}
}
✅ Bước 3: Tạo React App (app chính)
mkdir -p apps && cd apps
npx create-react-app web --template typescript
cd ../
Sửa apps/web/tsconfig.json
:
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"noEmit": true
},
"include": ["src"]
}
Sửa apps/web/package.json
:
{
"name": "web",
"version": "1.0.0",
"private": true,
"dependencies": {
"@myorg/ui": "*"
}
}
✅ Bước 4: Tạo UI Library (dùng Ant Design)
mkdir -p packages/ui/src
cd packages/ui
yarn init -y
yarn add antd
packages/ui/package.json
:
{
"name": "@myorg/ui",
"version": "1.0.0",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"build": "tsc"
},
"peerDependencies": {
"react": "^18.0.0",
"react-dom": "^18.0.0",
"antd": "^5.0.0"
}
}
packages/ui/tsconfig.json
:
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"declaration": true,
"outDir": "dist",
"composite": true
},
"include": ["src"]
}
Tạo MyButton
component:
📄
packages/ui/src/MyButton.tsx
import React from 'react';
import { Button } from 'antd';
type Props = {
label: string;
};
export const MyButton = ({ label }: Props) => {
return <Button type="primary">{label}</Button>;
};
📄
packages/ui/src/index.ts
export * from './MyButton';
✅ Bước 5: Dùng @myorg/ui
trong App
📄
apps/web/src/App.tsx
import React from 'react';
import { MyButton } from '@myorg/ui';
function App() {
return (
<div>
<h1>Hello from Monorepo</h1>
<MyButton label="Click Me" />
</div>
);
}
export default App;
✅ Bước 6: Cài dependency và chạy
# Từ thư mục gốc:
yarn install
# Build thư viện UI
cd packages/ui
yarn build
# Chạy App
cd ../../apps/web
yarn start
🧪 Kiểm tra
- Web chạy tại
localhost:3000
- Bạn thấy dòng Hello from Monorepo và một nút Click Me của Ant Design