ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Express에서 절대경로 세팅
    Node/Express 2022. 11. 28. 17:35

    Express에서 절대경로를 세팅하고 소스에 적용


    React 프로젝트에서 상대경로를 쓰게 되면 폴더가 깊어지면 깊어질수록 import할 때 ../../ 를 입력하는 경우가 많습니다.

    따라서 절대경로를 써서 @src/component/sample 이런 식으로 import하게 만듭니다.

    React에서 절대경로를 사용하고자 한다면 jsconfig.json / tsconfig.json이나 webpack을 건드려서 세팅할 수 있습니다.

     

    다만 Node Express에선 좀 다르고 제약사항이 있으며 어떻게 사용할 수 있는지 살펴보겠습니다.

     

    필요한 라이브러리: ts-node, tsconfig-paths

     

    • tsconfig.json & tsconfig.paths.json 소스
    // tsconfig.json
    {
    	"extends": "./tsconfig.paths.json",
    	"compilerOptions": {
    		"module": "Commonjs",
    		"target": "ES2015",
    		"sourceMap": true,
    		"allowJs": true,
    		"esModuleInterop": true,
    		"outDir": "./dist"
    	},
    	"include": ["src/**/*"],
    	"exclude": ["node_modules", "dist/**/*"]
    }
    
    
    // tsconfig.paths.json
    {
    	"compilerOptions": {
    		"baseUrl": ".",
    		"paths": {
    			"@src/*": ["src/*"]
    		}
    	}
    }

    src폴더를 기준으로 절대경로를 세팅했으니 불러올 때 from '@src/controllers/...' 로 불러오면 됩니다.

    React에선 @pages, @src, @styles 등 다 가능한데 Node express에선 테스트 했을 때 @src 하나만 가능했습니다.

    따라서 tsconfig.paths.json에 @src 하나만 넣었습니다.

     

    다만 이걸 한다고 끝이 아니라 ts-node, tsconfig-paths패키지를 설치 후  package.json에서도 바꿔야 할 것이 있습니다.

     

    • package.json
    "scripts": {
        "dev": "env-cmd -f .env.local nodemon --exec ts-node -r tsconfig-paths/register src/app.ts",
        "build": "tsc -p tsconfig.json",
        "startProduction": "env-cmd -f .env.production ts-node -r tsconfig-paths/register dist/app.js"
    },

    env-cmd 라이브러리로 환경변수가 담긴 파일을 명시해주고 (여기 예시에선 .env.local, .env.production) 개발환경에서 무언가를 바꾸면 nodemon이 알아서 서버를 재실행해줍니다.

    ts-node -r tsconfig-paths/register 를 꼭 해줘야 tsconfig.json에서 설정한 절대경로를 인식해서 불러올 수 있습니다.

     

    한번 개발소스랑 빌드된 dist폴더의 소스랑 비교를 해볼까요?

    // 개발 소스
    import asyncHandler from '@src/middleware/async';
    import { generateUID, LinkArrFetchMetadata } from '@src/util/customFunc';
    import ErrorResponse from '@src/util/errorResponse';
    
    
    // build를 실행하여 ES2015로 컴파일 된 소스
    const async_1 = __importDefault(require("@src/middleware/async"));
    const customFunc_1 = require("@src/util/customFunc");
    const errorResponse_1 = __importDefault(require("@src/util/errorResponse"));

    빌드된 소스에서도 @src/ 로 되어있기 때문에 ts-node -r tsconfig-paths/register 를 해주지 않으면 node에서 인식을 하지 못합니다.

    따라서 js로 변환된 dist/app.js를 실행할 때도 ts-node -r tsconfig-paths/register 를 명시적으로 입력해줘야 합니다

    (npm run startProduction 부분)

    'Node > Express' 카테고리의 다른 글

    Express MySql 연결 & Sql Injection 방어  (0) 2022.11.28
    Express에 소캣 연결하기 & 이벤트 분리  (0) 2022.11.27

    댓글

Designed by Tistory.