본문 바로가기
Programming/JavaScript

[TS] 기본 세팅

터미널에서 설치부터 하기

npm install -g typescript

 

 

 

 

공식 문서: https://www.typescriptlang.org/tsconfig/

tsconfig.json 기본 내용(ts 인식하려면 해당 파일 생성 필요)

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "noImplicitAny": true,  
        "strictNullChecks": true  
    }
}

 

이게 기본형태(IE 호환성 측면에서 무난함.)

target: js 버전 설정 (es5, es2016, esnext; 최신)
module: js 파일간 import 문법 설정 (commonjs: require,  ex2015 이후: import)

noImplicitAny": true,   // any type이 'any' 입력 없이 검출될 때 에러 출력(선택)
strictNullChecks": true  // null, undefine 에 이상한 조작시 에러 출력(선택)

 

 

 

 

자주 사용하는 것만 정리

 

 

{
 "compilerOptions": {

  "target": "es5", // 'es3', 'es5', 'es2015', 'es2016', 'es2017','es2018', 'esnext' 가능
  "module": "commonjs", //무슨 import 문법 쓸건지 'commonjs', 'amd', 'es2015', 'esnext'
  "allowJs": true, // js 파일들 ts에서 import해서 쓸 수 있는지 
  "checkJs": true, // 일반 js 파일에서도 에러체크 여부 
  "jsx": "preserve", // tsx 파일을 jsx로 어떻게 컴파일할 것인지 'preserve', 'react-native', 'react'
  "declaration": true, //컴파일시 .d.ts 파일도 자동으로 함께생성 (현재쓰는 모든 타입이 정의된 파일)
  "outFile": "./", //모든 ts파일을 js파일 하나로 컴파일해줌 (module이 none, amd, system일 때만 가능)
  "outDir": "./", //js파일 아웃풋 경로바꾸기
  "rootDir": "./", //루트경로 바꾸기 (js 파일 아웃풋 경로에 영향줌)
  "removeComments": true, //컴파일시 주석제거 

  "strict": true, //strict 관련, noimplicit 어쩌구 관련 모드 전부 켜기
  "noImplicitAny": true, //any타입 금지 여부
  "strictNullChecks": true, //null, undefined 타입에 이상한 짓 할시 에러내기 
  "strictFunctionTypes": true, //함수파라미터 타입체크 강하게 
  "strictPropertyInitialization": true, //class constructor 작성시 타입체크 강하게
  "noImplicitThis": true, //this 키워드가 any 타입일 경우 에러내기
  "alwaysStrict": true, //자바스크립트 "use strict" 모드 켜기

  "noUnusedLocals": true, //쓰지않는 지역변수 있으면 에러내기
  "noUnusedParameters": true, //쓰지않는 파라미터 있으면 에러내기
  "noImplicitReturns": true, //함수에서 return 빼먹으면 에러내기 
  "noFallthroughCasesInSwitch": true, //switch문 이상하면 에러내기 
 }
}

 

 

터미널: tsc -w   입력시 자동변환(갱신)모드 작동 -> 켜놓고 ts에 개발하면서, 실제 파일 사용시 js만 사용

tsc -w

 

 

 

 

 

 

 

 

 

<프레임워크별 환경 세팅법>


React 프로젝트에서 Typescript 사용할 경우 

 

1. 이미 있는 React 프로젝트에 설치하실거면

작업폴더경로에서 터미널을 오픈하신 후 

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

 

입력해주면 끝입니다. 이제 .js 파일을 .ts 파일로 바꿔서 이용가능합니다.

근데 뭔가 많아서 불안정하고 에러도 많이날 것 같죠?

그러면 yarn 1버전이 설치되어있으면 yarn add라는 명령어 쓰든가 

그냥 애초에 처음부터 Typescript 적용된 React 프로젝트를 생성할 수도 있습니다. 

 

 

2. 그냥 React 프로젝트를 새로 만들거면 

새로 작업폴더를 하나 만드시고 거기서 에디터와 터미널을 오픈한 다음 

npx create-react-app my-app --template typescript

입력해주면 끝입니다. 대시 두개임 

 

 


 

 

Vue 프로젝트에서 Typescript 사용할 경우

 

 

1. 작업폴더경로에서 터미널을 오픈하신 후 

vue add typescript

입력하면 라이브러리가 설치됩니다. 

 

 

2. 이제 vue파일에서 타입스크립트를 쓰려면 

<script lang="ts">
  
</script>

이렇게 lang 옵션을 켜두고 쓰면 알아서 잘 됩니다.

Vue 프로젝트 내에서도 tsconfig.json 파일 만들어서 설정도 자유롭게 가능합니다.

 

 

 

 


SAP UI5 프로젝트에서 Typescript 사용할 경우

 

처음부터 TypeScript 템플릿으로 생성 (권장)

가장 빠른 방법은 Yeoman 기반의 Easy-UI5 TypeScript 앱 템플릿을 사용하는 것입니다. UI5 & TypeScript

설치 및 생성 단계:

 
 
bash

 

# 1. Yeoman과 Easy-UI5 생성기 설치
npm install -g yo generator-easy-ui5

# 2. 생성기 설치 확인
yo --generators

# 3. TypeScript 앱 생성
yo easy-ui5 ts-app

생성 시 애플리케이션 이름, 네임스페이스, 프레임워크, 버전 등을 선택하라는 프롬프트가 나타납니다. SAP Blogs

 
 
bash
# 4. 프로젝트 실행
cd your-app-name
npm start

템플릿에 포함된 것:

  • 최신 모범 사례와 UI5 CLI 및 UI5 커뮤니티 확장을 통합한 Yeoman 생성기 GitHub
  • tsconfig.json
  • UI5 타입 정의
  • ui5-tooling-transpile 설정

기존 프로젝트에 TypeScript 적용

필요한 패키지 설치:

 
 
bash
npm install --save-dev typescript @sapui5/ts-types-esm
npm install --save-dev @ui5/cli @ui5/tooling-transpile-middleware
npm install --save-dev babel @babel/core @babel/preset-env @babel/preset-typescript

tsconfig.json 설정:

 
 
json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "es2022",
    "lib": ["ES2022", "DOM"],
    "moduleResolution": "bundler",
    "skipLibCheck": true,
    "strict": true,
    "sourceMap": true,
    "rootDir": "./webapp",
    "outDir": "./dist"
  },
  "include": ["webapp/**/*.ts"],
  "exclude": ["node_modules", "dist"]
}

ui5.yaml 수정:

ui5-tooling-transpile를 빌드 플러그인 및 미들웨어로 구성하여 TypeScript를 JavaScript로 변환합니다. GitHub

 
 
yaml
specVersion: "2.0"
metadata:
  name: your-app-name
type: application

server:
  customMiddleware:
    - name: fiori-tools-proxy
      afterMiddleware: compression
    - name: ui5-tooling-transpile-middleware
      beforeMiddleware: serveResources

build:
  customTasks:
    - name: ui5-tooling-transpile-task

파일 변환:

  • JavaScript 파일들을 .ts 확장자로 변경
  • Component.js를 Component.ts로 이름 변경 GitHub

 

 

 

참조링크:

 

공식 UI5 TypeScript 문서https://sap.github.io/ui5-typescript

TypeScript FAQhttps://github.com/SAP-docs/sapui5/blob/main/docs/02_Read-Me-First/typescript-faq-8439949.md

Hello World 예제https://github.com/SAP-samples/ui5-typescript-helloworld

상세 단계별 가이드https://github.com/SAP-samples/ui5-typescript-helloworld/blob/main/step-by-step.md

TypeScript 튜토리얼https://github.com/SAP-samples/ui5-typescript-tutorial

 

Easy-UI5 생성기https://github.com/ui5-community/generator-easy-ui5

ts-app 템플릿https://github.com/ui5-community/generator-ui5-ts-app

 

 

 

 

 

 

 

 

 

728x90
반응형