만약에 어떤 컴포넌트나, 기능을 개발한다고하면 기능과 역할에 따라서 파일을 분리해서 작성한다.
만약에 Components 라는 폴더 하위에 아래와같이 3개의 컴포넌트와 1개의 util 함수가 있다고 치면(index.ts 제외)
다른 컴포넌트에서 import 해서 사용할때, import 구문이 4개가 필요해진다.
import Title from "./components/Title";
import Subtitle from "./components/Subtitle";
import Content from "./components/Content";
import { console } from "./components/Console";
export default function App() {
console("hi");
return (
<div className="App">
<Title>제목이에요</Title>
<Subtitle>부제목 이에요</Subtitle>
<Content>내용에이요. 하하하하</Content>
</div>
);
}
지금은 예시가 그냥 'conponents' 폴더인데, 만약 비슷한 기능을하는 것들로 묶은 폴더별로 존재한다면 이렇게 각각 불러오는것 보다, 하나의 root 를 만들어주는 것이 가독성에 좀 더 좋을 수 있고, 기능별로 묶어서 export 하기 때문에 구조파악에도 도움이 될 수 있다.
어떻게 해야 할까?
CRA로 만든 프로젝트라면 폴더기반의 import, export 설정이 되어있어서, 폴더를 import 하면 폴더 하위에 index 파일을 찾아서 import 해준다.
이 특성을 활용하면 componens 폴더하위에 index.ts를 생성하고(사진에는 이미생성되어있음) 하래와 같이 작성해준다.
export { default as Title } from "./Title";
export { default as Content } from "./Content";
export { default as Subtitle } from "./Subtitle";
export * from "./Console";
복잡해보이지만 다른분법을 쓴게없다.
우선 index.ts 에서 필요한 모든 파일을 import 한것이고, 특이하다면 default 로 export 되는 항목들은 겹치기 때문에, as 키워드를 활용해서 별칭을 지어준 것이다.
이렇게되면 index.ts 파일에서는 Title, Content, Subtitle에서 export default 한 항목들과, Console 에서 export 한 항목들을 모두 가지고왔고, 그대로 export 해주고있다.
그러면 index.ts 는 필요한 모든 것을 export 하고있고, 위에서 말했듯, 폴더기반으로 import 가 동작하는 방식이 적용되면
components 폴더에서 모든걸 import 해갈 수 있게된다.
코드는 아래와같이 변경될 수 있다.
import { Title, Content, Subtitle, console } from "./components";
export default function App() {
console("hi");
return (
<div className="App">
<Title>제목이에요</Title>
<Subtitle>부제목 이에요</Subtitle>
<Content>내용에이요. 하하하하</Content>
</div>
);
}
이런 폴더기반으로 index파일을 import ,export 하도록 하려면 일반적인 node 환경에서는 node --experimental-specifier-resolution=node index 옵션을 붙여서 실행해주어야한다.
Modules: ECMAScript modules | Node.js v18.6.0 Documentation
Modules: ECMAScript modules# Introduction# ECMAScript modules are the official standard format to package JavaScript code for reuse. Modules are defined using a variety of import and export statements. The following example of an ES module exports a functi
nodejs.org
'Archive' 카테고리의 다른 글
JS에서 2차원 배열 동적으로 만들 때 주의할 점 (0) | 2022.07.17 |
---|---|
React Ionic 정리 (0) | 2022.07.15 |
CRA + Prettier + ESLint 적용하기 (0) | 2022.07.12 |
MVC 패턴과 Flux 패턴에 대한 고찰 (0) | 2022.07.10 |
React 앱 + AWS S3 + Cloud Front + Github Actions CICD 배포 정리 (0) | 2022.07.07 |