TIL

[TIL] 2021년 12월 20일

건브로 2021. 12. 20. 23:08

1. 오늘 공부한 것

TypeScript CLI 명령어와 속성

tsconfig.json 설정하기

 

 

2.  TypeScript CLI 명령어

오늘 타입스크립트 명령어와 속성에 대해서 공부했다.

tsc 파일명은 기본적으로 아는 컴파일 방식이다.

 

이 방식을 계속 사용한다면 

react와 같은 라이브러리를 사용하는 project를 다룰 때 힘들 것이다.

 

그래서 이번에 배운 것은 컴파일을 자동화하는 것과 전체적으로 어떻게 관리하는 지 배웠다.

 

 

1) tsc 파일명 -w 또는 tsc 파일명 --watch

이 명령어는 해당 파일을 수정할 때 자동적으로 컴파일 하게 끔한다.

 

2) tsc init

이 명령어는 타입스크립트 파일을 하나의 프로젝트에서 관리하기 쉽게 하기위해서 

tsconfig.json을 만드는 명령이다.

 

3) tsc

이 명령어는 tsconfig.json이 있을 때 사용 가능한 명령어이다.

내 프로젝트에 있는 타입스크립트 파일을 모두 자바스크립트 파일로 컴파일 하기 위해서 사용한다. 

 

4) tsc -w

이 명령어는 tsconfig.json이 있을 때 사용 가능한 명령어이다.

내 프로젝트에 있는 타입스크립트 파일을 모두 자동으로 컴파일 해주며, 계속 주기적으로 감시한다.

 

결국, 자바스크립트 파일을 건드릴 필요가 없고 타입스크립트 파일만 건들여도 프로젝트 관리가 된다.

 

3. tsconfig.json 설정하기

먼저, tsconfig.json 파일을 봐야한다.

 

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */

    /* Projects */
    // "incremental": true,                              /* Enable incremental compilation */
    // "composite": true,                                /* Enable constraints that allow a TypeScript project to be used with project references. */
    // "tsBuildInfoFile": "./",                          /* Specify the folder for .tsbuildinfo incremental compilation files. */
    // "disableSourceOfProjectReferenceRedirect": true,  /* Disable preferring source files instead of declaration files when referencing composite projects */
    // "disableSolutionSearching": true,                 /* Opt a project out of multi-project reference checking when editing. */
    // "disableReferencedProjectLoad": true,             /* Reduce the number of projects loaded automatically by TypeScript. */

    /* Language and Environment */
    "target": "es2016",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    // "lib": [],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */
    // "jsx": "preserve",                                /* Specify what JSX code is generated. */
    // "experimentalDecorators": true,                   /* Enable experimental support for TC39 stage 2 draft decorators. */
    // "emitDecoratorMetadata": true,                    /* Emit design-type metadata for decorated declarations in source files. */
    // "jsxFactory": "",                                 /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */
    // "jsxFragmentFactory": "",                         /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
    // "jsxImportSource": "",                            /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */
    // "reactNamespace": "",                             /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */
    // "noLib": true,                                    /* Disable including any library files, including the default lib.d.ts. */
    // "useDefineForClassFields": true,                  /* Emit ECMAScript-standard-compliant class fields. */

    /* Modules */
    "module": "commonjs",                                /* Specify what module code is generated. */
    // "rootDir": "./",                                  /* Specify the root folder within your source files. */
    // "moduleResolution": "node",                       /* Specify how TypeScript looks up a file from a given module specifier. */
    // "baseUrl": "./",                                  /* Specify the base directory to resolve non-relative module names. */
    // "paths": {},                                      /* Specify a set of entries that re-map imports to additional lookup locations. */
    // "rootDirs": [],                                   /* Allow multiple folders to be treated as one when resolving modules. */
    // "typeRoots": [],                                  /* Specify multiple folders that act like `./node_modules/@types`. */
    // "types": [],                                      /* Specify type package names to be included without being referenced in a source file. */
    // "allowUmdGlobalAccess": true,                     /* Allow accessing UMD globals from modules. */
    // "resolveJsonModule": true,                        /* Enable importing .json files */
    // "noResolve": true,                                /* Disallow `import`s, `require`s or `<reference>`s from expanding the number of files TypeScript should add to a project. */

    /* JavaScript Support */
    // "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
    // "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */
    // "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */

    /* Emit */
    // "declaration": true,                              /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
    // "declarationMap": true,                           /* Create sourcemaps for d.ts files. */
    // "emitDeclarationOnly": true,                      /* Only output d.ts files and not JavaScript files. */
    // "sourceMap": true,                                /* Create source map files for emitted JavaScript files. */
    // "outFile": "./",                                  /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */
    // "outDir": "./",                                   /* Specify an output folder for all emitted files. */
    // "removeComments": true,                           /* Disable emitting comments. */
    // "noEmit": true,                                   /* Disable emitting files from a compilation. */
    // "importHelpers": true,                            /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
    // "importsNotUsedAsValues": "remove",               /* Specify emit/checking behavior for imports that are only used for types */
    // "downlevelIteration": true,                       /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
    // "sourceRoot": "",                                 /* Specify the root path for debuggers to find the reference source code. */
    // "mapRoot": "",                                    /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,                          /* Include sourcemap files inside the emitted JavaScript. */
    // "inlineSources": true,                            /* Include source code in the sourcemaps inside the emitted JavaScript. */
    // "emitBOM": true,                                  /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
    // "newLine": "crlf",                                /* Set the newline character for emitting files. */
    // "stripInternal": true,                            /* Disable emitting declarations that have `@internal` in their JSDoc comments. */
    // "noEmitHelpers": true,                            /* Disable generating custom helper functions like `__extends` in compiled output. */
    // "noEmitOnError": true,                            /* Disable emitting files if any type checking errors are reported. */
    // "preserveConstEnums": true,                       /* Disable erasing `const enum` declarations in generated code. */
    // "declarationDir": "./",                           /* Specify the output directory for generated declaration files. */
    // "preserveValueImports": true,                     /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */

    /* Interop Constraints */
    // "isolatedModules": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */
    // "allowSyntheticDefaultImports": true,             /* Allow 'import x from y' when a module doesn't have a default export. */
    "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
    // "preserveSymlinks": true,                         /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */

    /* Type Checking */
    "strict": true,                                      /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                            /* Enable error reporting for expressions and declarations with an implied `any` type.. */
    // "strictNullChecks": true,                         /* When type checking, take into account `null` and `undefined`. */
    // "strictFunctionTypes": true,                      /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
    // "strictBindCallApply": true,                      /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */
    // "strictPropertyInitialization": true,             /* Check for class properties that are declared but not set in the constructor. */
    // "noImplicitThis": true,                           /* Enable error reporting when `this` is given the type `any`. */
    // "useUnknownInCatchVariables": true,               /* Type catch clause variables as 'unknown' instead of 'any'. */
    // "alwaysStrict": true,                             /* Ensure 'use strict' is always emitted. */
    // "noUnusedLocals": true,                           /* Enable error reporting when a local variables aren't read. */
    // "noUnusedParameters": true,                       /* Raise an error when a function parameter isn't read */
    // "exactOptionalPropertyTypes": true,               /* Interpret optional property types as written, rather than adding 'undefined'. */
    // "noImplicitReturns": true,                        /* Enable error reporting for codepaths that do not explicitly return in a function. */
    // "noFallthroughCasesInSwitch": true,               /* Enable error reporting for fallthrough cases in switch statements. */
    // "noUncheckedIndexedAccess": true,                 /* Include 'undefined' in index signature results */
    // "noImplicitOverride": true,                       /* Ensure overriding members in derived classes are marked with an override modifier. */
    // "noPropertyAccessFromIndexSignature": true,       /* Enforces using indexed accessors for keys declared using an indexed type */
    // "allowUnusedLabels": true,                        /* Disable error reporting for unused labels. */
    // "allowUnreachableCode": true,                     /* Disable error reporting for unreachable code. */

    /* Completeness */
    // "skipDefaultLibCheck": true,                      /* Skip type checking .d.ts files that are included with TypeScript. */
    "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
  }
}

여기서 오늘 공부한 것을 순서대로 적어보겠다.

 

1) exclude

exclude는 컴파일 하지 않을 타입스크립트 파일을 지정하는 key이다.

exclude의 값은 배열 형식이며, 배열 안에 파일이나 폴더를 넣으면 된다.

 

※ exclude에 node_modules를 넣을 필요는 없다. default로 지정되어 있기 때문

 

※ 와일드 카드(glob 패턴) 허용: 

<exclude의 값으로 존재할 때 예시>

*.dev.ts => 같은 프로젝트에서만 dev.ts라는 형식을 제외
**/*.dev.ts => 어디 폴더에 있든 간 dev.ts라는 형식을 제외.

 

=> include에서도 적용된다.

 

{
  "compilerOptions": {
    //생략
  },
  "exclude": [
    "node_modules"
  ]
}

 

2) include

include는 exclude와는 반대로 컴파일 할 타입스크립트 파일을 지정하는 key이다.

include에 포함된 파일이나 폴더 이름을 제외하고는 컴파일이 되지 않는다.

 

glob 패턴 허용한다.

 

{
  "compilerOptions": {
    //생략
  },
  "include": [
    "app.ts",
    "src/**/*", 
    "tests/**/*"
  ]
}

 

3) files

files는 include와 비슷한 성격을 가지고 있다. 

다만 glob 패턴을 허용하지 않기 때문에 소규모 프로젝트에 어울린다.

 

위의 코드처럼 glob 패턴을 사용하여 여러 개를 지정할 수 없다.

 

4)target

컴파일 할 때 어떤 자바스크립트 버전으로 컴파일 할 지 정한다.

현재 es2016 즉 es6로 적용된 걸 보여준다.

 

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */

    /* Projects */
    //생략
    /* Language and Environment */
    "target": "es2016",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    // "lib": [],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */
    // "jsx": "preserve",                                /* Specify what JSX code is generated. */
    //생략
  }
}

 

 

5)lib

target은 어떤 것으로 컴파일 할 지 정하는 key였다면,

lib는 타입스크립트가 어떤 파일이 .ts확장자일 때 어떻게 해석할 것인가이다.

처음엔 주석처리 되어 있어서 기본적인 자바스크립트를 제공하는 api로 구성되어있다.

 

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */

    /* Projects */
    //생략
    /* Language and Environment */
    "target": "es2016",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    // "lib": [],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */
    // "jsx": "preserve",                                /* Specify what JSX code is generated. */
    //생략
  }
}

 

 

const buttonEl = document.querySelector('.button');
//lib가 주석처리가 풀려있고 아무것도 지정해주지 않았다면 오류가 난다.
//이 코드가 오류가 나는 이유는 DOM API가 없기 때문이다.
//그러니 lib를 주석처리 하든지, lib안에 알맞은 자바스크립트 API를 넣으면 된다.

 

6)allowjs

allowjs는 자바스크립트 코드를 import 할 수 있는지 없는지 유무를 결정해준다.

true이면 타입스크립트에서 자바스크립트 변수 또는 파일을 export하는 것을 받아들일 수 있다.

 

기본적으로  false로 되어있다.

 

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */

    /* Projects */
    //생략

    /* Language and Environment */
    //생략
    
    /* JavaScript Support */
    // "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */
    // "checkJs": true,                                  /* Enable error reporting in type-checked JavaScript files. */
    // "maxNodeModuleJsDepth": 1,                        /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */

    //생략
  }
}

 

7)checkjs

 

checkjs는 allowjs랑 같이 쓰인다.

 

기능은 타입스크립트와 같이 사용할 다른 자바스크립트 코드에서

어떤 타입의 오류가 있는 지 알려주는 key이다.

 

 

 

4. 느낀점

처음에 타입스크립트의 타입을 배울 땐 어떻게 해서 

프로젝트에 녹여낼까 생각을 했다.

 

전체적으로 컴파일 해주는 명령어와 자동적으로 검사하며, 컴파일 해주는 명령어를 배우면서

막힌 곳이 뻥뚫린 느낌이었다.

 

항상 이론을 배울 땐 지루한 법이지만, 

그냥 이론을 배울 때와 어떻게 사용하면 될지 배울 때의 나의 관심도는 천차만별이다.

 

하지만, 편식을 해서는 안 된다.

 

이론을 공부하는 것을 싫어한다면,

누군가가 형식적으로 알려주는 것에 대해서만 학습하게 된다.

그렇게 된다면 난 양상형 코드를 찍어내는 로봇에 불과하다.

 

화이팅하자!!!

 

출처:

https://www.typescriptlang.org/ko/tsconfig#include

 

TSConfig Reference - Docs on every TSConfig option

From allowJs to useDefineForClassFields the TSConfig reference includes information about all of the active compiler flags setting up a TypeScript project.

www.typescriptlang.org

 

'TIL' 카테고리의 다른 글

[TIL] 2021년 12월 23일  (0) 2021.12.23
[TIL] 2021년 12월 21일  (0) 2021.12.21
[TIL] 2021년 12월 19일  (0) 2021.12.19
[TIL] 2021년 12월 18일  (0) 2021.12.18
[TIL] 2021년 12월 16일  (0) 2021.12.16