[Common] Absolute Path Settings

seohyun Kang·2022년 6월 22일
0

Common

목록 보기
1/8

Absolute Path를 사용해야하는 이유?

절대 경로를 사용하면 import하는데 "코드가 깔끔해 보이지 않을까?"라는 생각에 사용을 고민하게 되었습니다.

// Main.tsx

import {} from "../components/index"
import {} from "../../assets/~"
import {} from "../../some_dir"

프로젝트를 진행간에 디렉토리 구조를 다양하게 가져가면서 ../../../components/something과 같은 하위 디렉토리 지정을 회피하고자 절대경로를 사용하려고 합니다.

// Sample Dir Structure

root 
 ㄴ tsconfig.json // modify
 ㄴ config
 	ㄴ webpack.config.js // modify
    ㄴ ...etc
 ㄴ node_modules
 ㄴ src
 	ㄴ apis
    	ㄴ api.tsx
        ㄴ rest.tsx
        ㄴ sc.tsx
 	ㄴ components
    	ㄴ Common
        ㄴ LoginPage
        ㄴ ...Page
    ㄴ pages
    	ㄴ LoginPage.tsx

tsconfig.json webpack.config.js를 수정할 예정입니다.


How to set Absolute Path?

위에도 언급했지만 tsconfig.json과 webpack.config.js를 수정하겠습니다.

  • tsconfig.json
{
	"baseUrl" : "./",
    "paths" : {
    	"src/*" : ["./src/*"]
    },
	...etc 
}

"baseUrl" : 절대경로 시작 root path
"paths" : 절대 경로
  • webpack.config.js
module.export = {
	resolve : {
        alias: {
            src: path.resolve(__dirname, "../", "src"),
        },
    	modules : [path.resolve(__dirname, "../", "node_modules")]
    }
}

개발단에서는 tsconfig.json 수정만으로 compile되어 개발이 가능하지만 build하면서 webpack이 절대경로를 인지하지 못하여 webpack의 configuration을 변경해주어야 합니다.

0개의 댓글