타입스크립트로 리액트 프로젝트를 하던 중,
<FlexContainer />와 <GridContainer />
리스트를 간단히 map 돌려서 컴포넌트로 반환하는 로직 여러 군대에서 발견되어
혹시 번들링할 때 map 그대로 들어가나? 생각을 했다.
아래와 같은 구조를 통해 중복되는 부분을 추상화 했다.
일단 타입 정의 먼저,
export interface ItemProps {
id: number | string;
}
export type IteratingItemProps<T extends ItemProps> = {
items: T[];
component: ElementType;
};
export type IteratingLayoutProps<T extends ItemProps> = IteratingItemProps<T> & {
container: ElementType;
};
export type ItemsIteratorProps<T extends ItemProps> = IteratingLayoutProps<T> & {
otherProps?: object;
};
// export type FlexContainerProps<T extends ItemProps> = Omit<IContainerProps<T>, 'container'>;
export type FlexContainerProps<T extends ItemProps> = IteratingItemProps<T> & {
className?: string;
};
export type GridContainerProps<T extends ItemProps> = IteratingItemProps<T> & {
columns: number | object;
gap?: number;
className?: string;
};
중복되는 부분을 추상화 했다.
const IContainer = <T extends ItemProps>({
items,
component: Component,
container: Container,
otherProps = {},
}: IContainerProps<T>): ReactElement => {
return (
<Container {...otherProps}>
{items.map(({ id, ...props }) => (
<Component key={id} id={id} {...props} />
))}
</Container>
);
};
const FlexContainer = <T extends ItemProps>({
items,
component,
className = '',
}: FlexContainerProps<T>): ReactElement => {
return (
<IContainer items={items} component={component} container={FlatFlex} otherProps={{ className }} />
);
};
const GridContainer = <T extends ItemProps>({
items,
component,
columns,
gap = 0,
}: GridContainerProps<T>): ReactElement => {
return (
<IContainer
items={items}
component={component}
container={Grid}
otherProps={{ className, columns, gap }}
/>
);
};
map 로직만 분리시켰는데도 번들 사이즈가 줄었다.
map이 중복되는 만큼 더 사이즈가 줄어들 것으로 보아 좋은 시도였던 것 같다.
추상화 전 번들 사이즈 : 58073
추상화 후 번들 사이즈 : 58061
'Frontend > Typescript' 카테고리의 다른 글
[Typescript] node 환경에서 빌드하기 tsconfig.node.json (0) | 2025.03.09 |
---|