╱╱╭╮╱╱╱╱╱╱╭━━━╮╱╱╱╭╮╱╭╮╱╱╱╱╱╱ ╱╱┃┃╱╱╱╱╱╱┃╭━╮┃╱╱╱┃┃╱┃┃╱╱╱╱╱╱ ╱╱┃┣━━┳━━╮┃┃╱┃┣━╮╱┃╰━╯┣━━┳━╮╱ ╭╮┃┃╭╮┃┃━┫┃╰━╯┃╭╮╮┃╭━╮┃╭╮┃╭╮╮ ┃╰╯┃╭╮┃┃━┫┃╭━╮┃┃┃┃┃┃╱┃┃╭╮┃┃┃┃ ╰━━┻╯╰┻━━╯╰╯╱╰┻╯╰╯╰╯╱╰┻╯╰┻╯╰╯

Frontend/Typescript

[Typescript] map() 관련 번들 사이즈 줄이기

재안안 2024. 7. 7. 17:54

타입스크립트로 리액트 프로젝트를 하던 중,

<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