마이그레이션 순서

 

  1. Add TypeScript
  2. Add tsconfig.json
  3. Start simple
  4. Convert all files
  5. Increase strictness
  6. Clean it up
  7. Celebrate

 

1. typescript 설치

 

npm install --save typescript @types/node @types/react @types/react-dom @types/jest

yarn add typescript @types/node @types/react @types/react-dom @types/jest

를 통하여 typescript 및 기타 모듈을 설치한다.

 

기존 js 기반 react의 react-router-dom의 경우

npm install react-router-dom로 설치한다.

 

하지만 ts에서는 npm install @types/react-router-dom 로 설치를 새로 해야한다.

이 글의 마지막에 이 프로젝트에서 사용되어지는 @types/*의 package.json을 넣어두겠다.

 

위 문제의 에러 메시지는 보통 "  Could not find a declaration file for module 'react-redux'.  "와 같이

모듈을 찾을 수 없다고 나온다.

 

 

2. tsconfig.json 추가

 

tsconfig.json는 프로젝트를 컴파일하는 데 필요한 루트 파일과 컴파일러 옵션을 지정하는 파일입니다.

 

[참고사이트]

www.typescriptlang.org/docs/handbook/tsconfig-json.html

typescript-kr.github.io/pages/tsconfig.json.html

 

 

npx tsc --init

를 수행하여 생성하거나 직접 tsconfig.json 생성

 

아래는 npx tsc --init를 이용하여 기본적으로 생성되는 tsconfig.json 포맷.

더보기

{

  "compilerOptions": {

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

 

    /* Basic Options */

    // "incremental": true,                   /* Enable incremental compilation */

    "target""es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */

    "module""commonjs",                     /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', 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 */

    // "tsBuildInfoFile": "./",               /* Specify file to store incremental compilation information */

    // "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. */

    // "allowUmdGlobalAccess": true,          /* Allow accessing UMD globals from modules. */

 

    /* 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. */

 

    /* Advanced Options */

    "skipLibCheck"true,                     /* Skip type checking of declaration files. */

    "forceConsistentCasingInFileNames"true  /* Disallow inconsistently-cased references to the same file. */

  }

}

 

 

 

 

3. convert all files

 

사실 TS를 모르는 상태에서 TS 변환 후 배워나가겠다..라는 방법은 맞지 않다.

ts로 전환하는 과정에서는 기존 js에 ts의 type annotation을 일일히 수작업으로 맞추어주어야 하기 때문에

ts에 대한 문법적 지식이 전무한 상태에서는 진행하기가 힘들다고 생각이 된다.

 

tsconfig.json rule을 매우 느슨하게 설정(strict:false)하여 진행해볼수도 있다.

(본 작성자는 TS를 모르는 상태에서 작업을 진행하였다)

 

 

모든 js react프로젝트에 해당하는것은 아니지만, 적어도 내가 진행하는 프로젝트에서 나오는 문제점들을 하나하나 나열해가면서 진행한다.

 

1. 위에 말했던 react-router-dom이 ts버전인 package를 설치해야하는 문제.

 

2. 

상대경로 관련 문제

 

 

import App from "app"; 부분을 보자.

정확히는 tsconfig.json의 "moduleResolution""node", << 이 옵션에 관한 문제.

 

chiabi.github.io/2018/08/30/typescript/

www.typescriptlang.org/docs/handbook/module-resolution.html .

 

세부적인 moduleResolution은 위의 링크에서 확인하길 바랍니다.

필자는 import App from "./App"; << 로 상대경로를 지정했습니다.

해당 옵션을 보고, node로 설정 후 require로 끌어오는 것을 추천드립니다.

 

 

+ Recent posts