React

커스터마이징, 혹은 특정 컴포넌트만 사용하고 싶은 경우에 pro-components 패키지를 직접 설치하지 않고 소스 코드를 가져다가 직접 쓰는 방법

오아름 샘 2025. 6. 19. 16:22
반응형

Ant Design Pro에서 제공하는 고급 컴포넌트들(`@ant-design/pro-components`)은 기업용 어드민 UI를 빠르게 구성할 수 있도록 도와주는 강력한 라이브러리입니다.  
하지만 때로는 번들 크기 최적화, 커스터마이징, 혹은 특정 컴포넌트만 사용하고 싶은 경우에 `pro-components` 패키지를 직접 설치하지 않고 **소스 코드를 가져다가 직접 쓰고 싶을 수 있습니다**.

---

## ✅ 목표

- `@ant-design/pro-components` 패키지 설치 없이도
- 필요한 컴포넌트(예: `ProTable`, `ProForm`, `Descriptions`, 등)의 소스코드를 직접 가져와서 사용

---

## 🚀 방법 1: GitHub에서 원본 소스 가져오기 (추천)

공식 저장소에서 각 컴포넌트의 소스 코드를 볼 수 있고, 필요한 파일만 프로젝트에 복사해서 사용하면 됩니다.

### 🔗 공식 GitHub 주소:
- [https://github.com/ant-design/ant-design-pro/tree/master/src/components](https://github.com/ant-design/ant-design-pro/tree/master/src/components)

각 컴포넌트 예시:

| 컴포넌트 | 경로 |
|---------|------|
| `ProTable` | [`/src/components/ProTable`](https://github.com/ant-design/ant-design-pro/tree/master/src/components/ProTable) |
| `ProForm` | [`/src/components/ProForm`](https://github.com/ant-design/ant-design-pro/tree/master/src/components/ProForm) |
| `Descriptions` | [`/src/components/Descriptions`](https://github.com/ant-design/ant-design-pro/tree/master/src/components/Descriptions) |

---

## 🛠️ 단계별 실습: `ProTable` 직접 가져오기

### Step 1. GitHub에서 `ProTable` 소스 다운로드

예: [ProTable.tsx](https://github.com/ant-design/ant-design-pro/blob/master/src/components/ProTable/index.tsx)

> 해당 파일과 관련된 의존성 파일들(예: `components/`, `utils/`, `types/` 폴더 등)도 함께 복사해야 합니다.

### Step 2. 프로젝트에 붙여넣기

프로젝트 내부에 다음과 같은 구조로 폴더 생성:

```
src/
 └── components/
     └── ProTable/
         ├── index.tsx
         ├── components/
         ├── utils/
         └── types/
```

### Step 3. import 경로 수정

복사한 파일 내부에서 상대 경로나 절대 경로가 맞는지 확인 및 수정:

```ts
// 원래 경로 (ant-design-pro 기준)
import { useMountMergeState } from '@/utils';

// 수정 후 (프로젝트 기준)
import { useMountMergeState } from '../../utils';
```

---

## 🧩 방법 2: 필요한 부분만 추출하여 간단하게 사용

모든 소스를 복사하기에는 너무 무겁거나 복잡하다면, **필요한 기능만 추출**해 간단한 버전으로 재구성할 수도 있습니다.

예: 기본 `Table` + 검색 조건 + 페이징만 필요하다면 아래처럼 축소 가능:

```tsx
import React, { useState } from 'react';
import { Table, Form, Input, Button } from 'antd';

const SimpleSearchTable = ({ columns, request }) => {
  const [form] = Form.useForm();
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({ current: 1, pageSize: 10 });

  const fetchData = async (params = {}) => {
    setLoading(true);
    const result = await request(params);
    setData(result.data);
    setPagination({
      ...params.pagination,
      total: result.total,
    });
    setLoading(false);
  };

  return (
    <div>
      <Form form={form} onFinish={(values) => fetchData({ ...values, pagination })}>
        <Form.Item label="검색어" name="keyword">
          <Input placeholder="입력하세요" />
        </Form.Item>
        <Button htmlType="submit">검색</Button>
      </Form>
      <Table
        loading={loading}
        columns={columns}
        dataSource={data}
        pagination={{
          ...pagination,
          onChange: (page, pageSize) =>
            fetchData({ pagination: { current: page, pageSize } }),
        }}
      />
    </div>
  );
};

export default SimpleSearchTable;
```

---

## 📦 방법 3: `unplugin-react-components`로 Tree-shaking 대체 (번들 최적화)

만약 실제로 일부 컴포넌트만 사용하고 싶다면, 전체 소스를 가져오지 않아도 **on-demand 방식으로 필요한 것만 로드**할 수 있습니다.

### 설치:

```bash
npm install -D unplugin-react-components
```

### 설정 (`vite.config.ts` 예시):

```ts
import Components from 'unplugin-react-components/vite';
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [
    react(),
    Components({
      dts: true,
      include: [/\.tsx?$/, /\.jsx?$/],
      // Ant Design Pro 컴포넌트 자동 로딩
      resolvers: [],
    }),
  ],
});
```

> 이 방식은 여전히 `@ant-design/pro-components`를 설치해야 하지만, 불필요한 코드는 제거되어 번들이 최적화됩니다.

---

## 📌 참고: 필요한 유틸리티 함수들

Ant Design Pro 컴포넌트들은 다음과 같은 유틸리티 함수들을 많이 사용합니다:

- `useMountMergeState` – 초기값 + 외부값 처리
- `request` – 데이터 요청 핸들러
- `Field` – 폼 필드 래퍼
- `FooterRender` – 테이블 하단 커스텀

이 유틸리티 함수들도 아래 경로에서 찾을 수 있습니다:

🔗 [https://github.com/ant-design/ant-design-pro/tree/master/src/utils](https://github.com/ant-design/ant-design-pro/tree/master/src/utils)

---

## ✅ 결론

> `@ant-design/pro-components`를 설치하지 않고도,  
> GitHub에서 원본 소스를 직접 가져와서 필요한 컴포넌트만 사용하거나,  
> 그 아이디어를 기반으로 가벼운 커스텀 컴포넌트를 만들 수 있습니다.

---

## 🎁 추가 옵션: CLI 스크립트로 자동화

필요하시면 GitHub API를 활용해 특정 컴포넌트(`ProTable`, `ProForm` 등)의 모든 파일을 한 번에 다운로드하고,  
프로젝트 폴더에 자동으로 넣는 Node.js 스크립트도 만들어 드릴 수 있어요!

---

궁금하신 부분이나, 특정 컴포넌트를 어떻게 커스터마이징하고 싶으신지 말씀해주세요 😊  
그에 맞춰 더 구체적인 예제나 도움을 드릴 수 있습니다!

반응형