프론트엔드 개발/Typescript

타입스크립트 04. 브라우저에서 디버깅, outDir, rootDir

하이고니 2023. 2. 17. 08:38

디버깅


 

타입스크립트를 컴파일한 뒤 lite-server로 개발 과정을 체크할 때,

sources 탭을 보면 js 파일들만 있는 것을 확인할 수 있다.

 

tsconfig.json 파일을 조금 수정하면 ts 파일을 디버깅 할 수 있다.

 

{
  "compilerOptions": {
    /* Basic Options */
    "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
    "module": "commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    // "lib": [],                             /* Specify library files to be included in the compilation. */
    // "allowJs": true,                       /* Allow javascript files to be compiled. */
    // "checkJs": true,                       /* Report errors in .js files. */
    // "jsx": "preserve",                     /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    // "declaration": true,                   /* Generates corresponding '.d.ts' file. */
    // "declarationMap": true,                /* Generates a sourcemap for each corresponding '.d.ts' file. */
    // "sourceMap": true,                     /* Generates corresponding '.map' file. */
    // "outFile": "./",                       /* Concatenate and emit output to single file. */
    // "outDir": "./",                        /* Redirect output structure to the directory. */
    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                     /* Enable project compilation */
    // "removeComments": true,                /* Do not emit comments to output. */
    // "noEmit": true,                        /* Do not emit outputs. */
    // "importHelpers": true,                 /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,            /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,               /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    "strict": true,                           /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                 /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,              /* Enable strict null checks. */
    // "strictFunctionTypes": true,           /* Enable strict checking of function types. */
    // "strictBindCallApply": true,           /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
    // "strictPropertyInitialization": true,  /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                  /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                /* Report errors on unused locals. */
    // "noUnusedParameters": true,            /* Report errors on unused parameters. */
    // "noImplicitReturns": true,             /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,    /* Report errors for fallthrough cases in switch statement. */

    /* Module Resolution Options */
    // "moduleResolution": "node",            /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                       /* Base directory to resolve non-absolute module names. */
    // "paths": {},                           /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                        /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                       /* List of folders to include type definitions from. */
    // "types": [],                           /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true,  /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    "esModuleInterop": true                   /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,              /* Do not resolve the real path of symlinks. */

    /* Source Map Options */
    // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */
  }
  // "exclude": [
  //   "node_modules"   // would be the default
  // ]
}

 

이렇게 어마어마한 옵션들을 볼 수 있는데,

다른 건 건들지 말고 "sourceMap": true 부분만 주석 처리를 해제해주면 된다.

 

{
  "compilerOptions": {
	
    ...
    
    "sourceMap": true,                     /* Generates corresponding '.map' file. */
    
    ...
    
    /* Source Map Options */
    // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    // "experimentalDecorators": true,        /* Enables experimental support for ES7 decorators. */
    // "emitDecoratorMetadata": true,         /* Enables experimental support for emitting type metadata for decorators. */
  }
  // "exclude": [
  //   "node_modules"   // would be the default
  // ]
}

 

 

개발자도구에 ts 파일이 포함되어 있는 것을 확인할 수 있죠?

 

 

컴파일 경로 지정


 

큰 프로젝트 단위의 개발을 할 때,

기본적으로 루트 레벨에 있는 프로젝트 폴더에는 파일을 넣지 않는다.

 

보통 src 폴더와 dist 폴더를 사용해 파일들을 정리한다. (적어도 내가 듣고 있는 강의에서는 그렇다.)

 

src 폴더는 모든 타입스크립트 파일을 보관하고, dist 폴더는 모든 출력값을 보관하는 작업을 수행한다.

 

 

디폴트 세팅에서 타입스크립트 디컴파일러는 루트 레벨에 있는 폴더를 들여다보기 때문에,

위와 같은 방식으로 타입스크립트 파일 옆에 js 파일이 출력되게 하면 안 된다.

 

이럴 때, tsconfig.jsonoutDir을 설정하면 생성된 파일이 저장되는 위치를 디컴파일러에게 알릴 수 있다.

 

 

<tsconfig.json 생기게 하는 방법 링크>

 

타입스크립트 03. 컴파일 자동으로 (watch mode), tsconfig.json

watch mode 타입스크립트를 사용하면 변경 사항이 생길 때마다 터미널에 tsc 파일명.ts을 입력해줘야 브라우저 상에서 제대로 작동하는지 확인할 수 있다. 이 작업이 번거롭다면 watch mode를 사용하면

hajongon.tistory.com

 

tsconfig.json 파일의 outDir 옵션을 "./dist"로 설정하면 js 파일이 dist 폴더에 생성된다.

 

{
  "compilerOptions": {

    ...
    
    "outDir": "./dist",                        /* Redirect output structure to the directory. */
    // "rootDir": "./",                       /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
 	
    ...
    
  }
}

 

 

구조가 한 눈에 들어온다.

 

 

 

당연히 index.html 에서도 js 파일을 읽어올 경로를 수정해줘야 한다.

 

 

다음과 같이 src 폴더 안에 하위 폴더가 하나 더 있는 경우를 보자.

 

 

이 상태로 컴파일하게 되면,

 

 

위와 같이 같은 이름의 폴더가 dist 폴더 내에도 생성된다. 아름답지 않은가?

 

 

그 밑에 있는 "rootDir" 옵션은 뭘까?

 

rootDir 옵션은 루트 디렉토리를 설정하여 타입스크립트 컴파일러가 src 폴더만 컴파일할 수 있게 해준다.

그리고 outDir 에서도 그 구조가 유지되는지 확인한다.

 

rootDir 옵션을 설정해두지 않으면

 

 

이렇게 다른 폴더에 존재하는 ts 파일까지 컴파일한다.