이전 글인 Node.js 서버 구축하기를 기반으로 설명합니다.😊
import 시에 상대 경로를 사용한다면, 현재 위치를 생각하면서 작성해야합니다.
절대 경로로 사용하면 코드도 깔끔해지고, 자신이 설정한 기준 경로로 사용되니 이해하기도 더 쉽습니다.
// as-is
import test from '../../../../../../services/test.js';
// to-be
import test from '@/services/test.js';
절대 경로는 간단하게 설정할 수 있습니다.
{
"compilerOptions": {
중략...,
"baseUrl": "./",
"paths": {
"@/*": ["src/*"],
},
중략...,
},
}
위와 같이 설정한다면 src 하위의 파일들은
@/로 불러오겠다.
로 해석할 수 있습니다.
baseUrl
: 절대 경로의 기준이 되는 경로
paths
: 원하는 경로에 별칭을 지어 절대 경로 사용
// as-is
import test from './app';
// to-be
import test from '@/app';
💡 다중 경로도 사용할 수 있어요!
{ "compilerOptions": { 중략..., "baseUrl": "./", "paths": { "@test": ["src/test/*"], "@controller": ["src/controller/*"], }, 중략..., }, }
// as-is import test from './test/test'; import testController from './controller/testController'; // to-be import test from '@test/test'; import testController from '@controller/testController';
설정이 끝났다면 실제 import문도 절대 경로로 변경해봅시다.
// index.ts
import http from "http";
import app from "@/app"; // 👈 이 부분!
const PORT = 3000;
const server = http.createServer(app);
server.listen(PORT, () => {
console.log(`Start service on ${PORT} port!`);
});
이렇게 하고 시작을 해보면..
에러 발생 ?!?!😡
절대 경로로 설정한 부분때문에 안 되는 것 같은데..
우리가 Typescript에 설정을 했지만, 실제 ts-node는 설정한 별칭과 경로를 이해하지 못합니다.
그래서 tsconfig-paths
를 설치해 해결해보겠습니다.
# 모듈 설치
$ npm i -D tsconfig-paths
설치한 모듈은 node 실행 시 preload 될 수 있도록 설정해줍니다.
-r
: 실행 시 미리 로드할 모듈 설정
// package.json
{
중략...,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "nodemon --exec \"ts-node tsconfig-paths/register src\"", // 👈 이 부분!
"build": "tsc -p .",
},
중략...,
}
이제 다시 실행해보면..
서버가 잘 돌아갑니다!
빌드도 정상인지 확인해야겠죠?
# 빌드하기
$ npm run build
일단 문제는 없어보이는데... 수정했던 index.js
를 한 번 열어보겠습니다.
// dist/index.js
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const http_1 = __importDefault(require("http"));
const app_1 = __importDefault(require("@/app")); // 👈 이 부분!
const PORT = 3000;
const server = http_1.default.createServer(app_1.default);
server.listen(PORT, () => {
console.log(`Start service on ${PORT} port!`);
});
7번째 줄에 @
가 그대로 있습니다..
이러면 실행할 때 경로를 찾을 수 없다는 에러가 또 발생할겁니다.
이런 상황에서 별칭을 상대경로로 바꿔주는 모듈이 바로 tsc-alias
입니다.
# 모듈 설치
$ npm i -D tsc-alias
설치 후 scripts를 한 번 수정해보겠습니다.
// package.json
{
중략...,
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "nodemon --exec \"ts-node tsconfig-paths/register src\"",
"build": "tsc -p . && tsc-alias", // 👈 이 부분!
},
중략...,
}
tsc가 빌드를 다 완료한 후, 상대 경로로 바꿔주는 작업을 추가로 한 번 더 해주는 방식입니다.
결과는..?
// dist/index.js
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const http_1 = __importDefault(require("http"));
const app_1 = __importDefault(require("./app"));
const PORT = 3000;
const server = http_1.default.createServer(app_1.default);
server.listen(PORT, () => {
console.log(`Start service on ${PORT} port!`);
});
이제 정말 다 됐습니다!!
성공입니다!! 절대경로를 사용할 수 있는 환경을 만들었습니다.🎉