본문 바로가기
Tip&News

React 프로젝트(초기) JavaScript에서 TypeScript로 변경하기

by hongreat 2024. 12. 7.

기존 JavaScript 기반으로 만들어진 React 프로젝트를 TypeScript로 변경하는 과정을 기록합니다.

 

 

TypeScript Version - 5.7.2

React Version - 18.3.1

 

 

목차

     

    패키지 설치

     

     

    TypeScript와 React의 타입 정의를 프로젝트에 추가해야 합니다

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

     

     

    그러면 이렇게 아래 부분이 추가됩니다.

    package.json 과 package-lock.json 이 변경된 모습은 아래와 같습니다.

    package.json / package-lock.json

     

    TypeScript 설정 파일

    npx tsc --init

    tsconfig.json 파일을 생성합니다.

    위 코드를 입력하면 아래 내용이 생성됩니다.

     

     

    {
    "compilerOptions": {
    /* Visit https://aka.ms/tsconfig to read more about this file */
    /* Projects */
    // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
    // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
    // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
    // "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 legacy experimental 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. */
    // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
    /* Modules */
    "module": "commonjs", /* Specify what module code is generated. */
    // "rootDir": "./", /* Specify the root folder within your source files. */
    // "moduleResolution": "node10", /* 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. */
    // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
    // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
    // "rewriteRelativeImportExtensions": true, /* Rewrite '.ts', '.tsx', '.mts', and '.cts' file extensions in relative import paths to their JavaScript equivalent in output files. */
    // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
    // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
    // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
    // "noUncheckedSideEffectImports": true, /* Check side effect imports. */
    // "resolveJsonModule": true, /* Enable importing .json files. */
    // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
    // "noResolve": true, /* Disallow 'import's, 'require's or ''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. */
    // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
    // "noEmit": true, /* Disable emitting files from a compilation. */
    // "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. */
    // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
    // "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. */
    // "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. */
    /* Interop Constraints */
    // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
    // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
    // "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */
    // "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. */
    // "strictBuiltinIteratorReturn": true, /* Built-in iterators are instantiated with a 'TReturn' type of 'undefined' instead of 'any'. */
    // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
    // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
    // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
    // "noUnusedLocals": true, /* Enable error reporting when 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, /* Add 'undefined' to a type when accessed using an index. */
    // "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. */
    }
    }
    app.js와 index.js 의 js 를 tsx 로 변경합니다.

     


    기본 설정은 대부분 주석 처리되어 있으며, 프로젝트 요구사항에 맞게 조정할 수 있게 되어있습니다.

    너무 많아서 하나씩 보기보다 핵심적인 내용 만 찾아서 남겼습니다.

     

    그 핵심 설정 사항(기본)은 아래 사항들입니다.

    • "target": "es2016"(컴파일될 JavaScript의 ECMAScript 버전입니다.)
    • "module": "commonjs"(모듈 시스템 설정)
    • "strict": true (타입 검사를 엄격하게 할 것인지?)
    • "esModuleInterop": true (CommonJS 모듈 import 호환성을 개선할 것인지)

     

     

    파일 확장자 변경

    JavaScript 파일을 TypeScript 파일로 변환합니다.
    앱 시작 후 대표적인 파일들만 변경했습니다.

    가장 기본적으로 생성되는 파일들

     

    • app.jsapp.tsx
    • index.jsindex.tsx
    • reportWebVitals.jsreportWebVitals.ts

    타입 정의

    기존에 작성해둔 코드가 일부라도 있다면, TS로 변환하면서 타입을 지정해야 합니다.

     

     

    Props 타입 정의

    type GreetingProps = { 
      name: string; 
    }; 
    function Greeting({ name }: GreetingProps) { 
      return <h1>Hello, {name}!</h1>;
    }

    useState 타입 지정

    useState에도 타입을 지정해야합니다.
    기존에는 number와 같은 지정없이도 실행되었습니다.

    const [count, setCount] = useState<number>(0);

    배열 및 map 메서드 타입 지정

    const skills: string[] = ["Python", "Django","JavaScript", "React", "CSS"]; 
    function App() { 
      return ( 
        <ul> 
          {skills.map((item: string, index: number) => (
            <li key={index}>{item}</li>
          ))} 
        </ul>
      );
    }

    reportWebVitals.ts

    react 생성 기본 커맨드를 실행하면 reportWebVitals 라는 파일도 자동으로 생성됩니다.

    import { ReportHandler } from "web-vitals";
    const reportWebVitals = (onPerfEntry?: ReportHandler) => {
      if (onPerfEntry && onPerfEntry instanceof Function) {
        import("web-vitals").then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
          getCLS(onPerfEntry);
          getFID(onPerfEntry);
          getFCP(onPerfEntry);
          getLCP(onPerfEntry);
          getTTFB(onPerfEntry);
        });
      }
    };
    export default reportWebVitals;

    TypeScript로의 마이그레이션은 초기에는 다소 번거롭습니다.
    JavaScript로 만들어진 특정 프로젝트를 필수로 변경을 해야하는 상황이 있다면 어떤 것일지 궁금합니다.
    프로젝트 초반이 아닌 경우 변경하는 경우는 다양한 사이드 이펙트를 고려해야 할 것이며, 차라리 새로 만드는 것이 좋지 않을까 생각합니다.