Skip to content
On this page

2020-11-24

Title
2020-11-24
Category
2020
Tags
Aliases
2020-11-24
Created
3 years ago
Updated
last year

ts-node 절대경로

ts-node 라이브러리 설치

bash
yarn add -D typescript @types/node nodemon ts-node tsconfig-paths
yarn add -D typescript @types/node nodemon ts-node tsconfig-paths

package.json에서 nodemon으로 실행

json
"scripts": {
  "dev": "nodemon -r ts-node src/index.ts" // nodemon src/index.ts로도 실행됨
}
"scripts": {
  "dev": "nodemon -r ts-node src/index.ts" // nodemon src/index.ts로도 실행됨
}

tsconfig.json에 baseUrl과 path 설정

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

→ 이제 컴파일은 되지만, 컴파일된 파일을 node, ts-node가 인식하지 못한다.

→ tsconfig-paths 모듈로 가능

json
"scripts": {
  "dev": "nodemon --exec ts-node -r tsconfig-paths/register src/index.ts"
}
"scripts": {
  "dev": "nodemon --exec ts-node -r tsconfig-paths/register src/index.ts"
}

빌드 후에도 동작하게 하려면

  1. ts-node 모듈을 통해 작동시키는 방법이 있다.

    json
    "scripts": {
    	"start": "ts-node -r tsconfig-paths/register dist/index.js"
    	// 또는
    	// "start": "node -r ts-node/register/transpile-only -r tsconfig-paths/register dist/index.js"
    }
    
    "scripts": {
    	"start": "ts-node -r tsconfig-paths/register dist/index.js"
    	// 또는
    	// "start": "node -r ts-node/register/transpile-only -r tsconfig-paths/register dist/index.js"
    }
    
  2. tsconfig-paths의 bootstrap을 사용하는 방법.

    javascript
    // tsconfig-paths-bootstrap.js
    const tsConfigPathFile = require('./tsconfig.paths.json');
    const tsConfig = require('./tsconfig.json');
    const tsConfigPaths = require('tsconfig-paths');
    
    tsConfigPaths.register({
    	baseUrl: tsConfig.compilerOptions.outDir,
    	paths: tsConfigPathFile.compilerOptions.paths,
    });
    
    // tsconfig-paths-bootstrap.js
    const tsConfigPathFile = require('./tsconfig.paths.json');
    const tsConfig = require('./tsconfig.json');
    const tsConfigPaths = require('tsconfig-paths');
    
    tsConfigPaths.register({
    	baseUrl: tsConfig.compilerOptions.outDir,
    	paths: tsConfigPathFile.compilerOptions.paths,
    });
    
    json
    // package.json
    "scripts" {
      "start": "node -r ./tsconfig-paths-bootstrap.js dist/src/index.js"
    }
    
    // package.json
    "scripts" {
      "start": "node -r ./tsconfig-paths-bootstrap.js dist/src/index.js"
    }
    

참고자료

타입스크립트에서 절대경로 쓰기

typescript + node absolute path

Released under the MIT License.