Typescript 컴파일러 실행
기본적인 타입스크립트 컴파일러 실행 명령어 :
tsc app.ts
위의 명령어를 실행하게 되면 ts파일이 컴파일되어 js 파일로 새로 생성된다.
하지만, 이 명령어를 사용하게 되면 매번 파일 수정이 있을 때마다 매번 새로 실행 시켜줘야한다.
이를 해결하기 위해서는 아래의 "감시모드"를 이용하면 된다.
감시모드(Typescript watch mode)
: 파일이 변경될 때마다 타입스크립트가 다시 컴파일하도록 파일을 감시하라고 하는 것.
tsc app.ts --watch
// 또는
tsc app.ts -w
터미널에 이렇게 쓰게 되면 해당 파일에 대해 감시 모드가 되고, 파일에서 무언가를 변경하고 저장하면 dist에 있는 파일이 변경되고 자동으로 다시 컴파일된다.
파일의 변경점이 있을 때마다 자동으로 컴파일 시켜준다는 장점이 있지만, 단점으로는 파일을 여전히 타게팅해야한다는 불편함이 있다.
이 문제 또한 아래의 "컴파일러에서 파일을 관리하는 방법"을 참고하는 것이 좋다.
컴파일러에서 파일을 관리하는 방법
❓ 만약 컴파일해야하는 파일이 여러개라면?
tsc --init
이 명령은 한 번만 하면 된다. 타입스크립트 프로젝트로 초기화하고 싶은 프로젝트에서 실행한다.
즉, 타입스크립트에게 이 명령을 실행하는 폴더에 있는 모든 것에 대해 실행하라고 하는 것이다. 따라서 올바른 폴더에서 하는 것이 중요하다. 이 명령어를 입력하게 되면 tsconfig.json 파일이 생성되게 된다.
tsconfig 파일
tsconfig 파일은 타입스크립트를 위한 프로젝트 파일 표시기이다. 이 폴더에 있는 프로젝트와 모든 하위폴더는 타입스크립트로 관리되어야 한다.
tsc --init 명령어를 입력해 tsconfig 파일이 생성되었으면 tsc 뒤에 아무 것도 입력할 필요 없이 tsc만 입력해도 모든 폴더의 ts 파일들이 컴파일 된다.
이것 또한 감시모드와 결합될 수 있는데 tsc -w 또는 tsc --watch와 함께 쓸 수 있다.
❓ 전체 파일에서 일부 파일을 컴파일하고 싶지 않다면?
// tsconfig파일
{
"compilerOptions": {
/* Basic Options */
"target": "es6", /* 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": [
"dom",
"es6",
"dom.iterable",
"scripthost"
], /* 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": "./dist", /* Redirect output structure to the directory. */
"rootDir": "./src", /* 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'). */
"noEmitOnError": true,
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": false, /* 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
]
}
tsconfig파일은 위와 같이 compilerOption{{옵션내용}}과 같이 되어 있다. 이 때, compilerOption{{옵션내용}, "exclude": ["analytics"]}와 같이 exclude 옵션을 넣어 배열 안에 컴파일 시키지 않을 파일들을 넣는다.
❓ 이름이 중복되는 여러 파일을 컴파일하고 싶지 않다면?
analytics 라는 파일이 있고, dev.ts로 끝나는 모든 파일을 컴파일 하고 싶지 않다면 "*.dev.ts"라고 쓰면 dev.ts로 끝나는 모든 파일들이 컴파일되지 않는다( * : 와일드 카드)
"exclude": [
"*.dev.ts"
]
"exclude": [
"**/*.dev.ts"
]
// 이러한 패턴이 있는 파일은 어느 폴더에 있든지 무시한다는 것
기본적으로 exclude 안에는 "node_modules"를 넣는다(일반적으로 node_modules는 컴파일 목록에서 제외된다). exclude 옵션을 전혀 지정하지 않으면 node_modules는 자동으로 제외된다.
이와는 반대로 include 옵션을 사용할 수도 있다. 컴파일 프로세스에 포함할 파일을 타입스크립트에 구체적으로 지정해 줄 수 있다. 여기 나열되지 않은 파일은 컴파일되지 않는다.
❓ exclude 옵션과 include 옵션을 함께 사용한다면?
exclude 옵션과 include 옵션을 함께 사용한다면 include에서 exclude를 뺀 파일들이 컴파일된다.
추가적으로 files 옵션이 존재한다.
기본적으로 include옵션과 비슷하다. 하지만 include는 포함시키고 싶은 폴더 전체를 지정할 수 있었지만 files에서는 컴파일하려는 개별 파일만 지정할 수 있다. 따라서 프리 파일로만 작업하는 소규모 프로젝트에 적합한 옵션일 수 있다.
'TypeScript' 카테고리의 다른 글
Typescript 컴파일러 옵션 (2) | 2023.12.27 |
---|