728x90
반응형

기존 js로 되어있던 프로젝트를 typescript로 변경해야 될 때가 있다.

 

1. 필요한 패키지 다운로드

$ npm i typescript ts-loader @types/node @types/react @types/react-dom @types/jest --dev

2. tsc 명령어 안먹힘

window로 작업하던 중 tsc 명령어가 안 먹히는 것을 보고 해결법을 찾았다. 아래와 같은 오류일 때 가능하다.

tsc : 'tsc' 용어가 cmdlet, 함수, 스크립트 파일 또는 실행할 수 있는 프로그램 이름으로 인식되지 않습니다. 
 이름이 정확한지 확인하고 경로가 포함된 경우 경로가 올바른지 검증한 다음 다시 시도하십시오.

 

window 파워 셀을 관리자 권한으로 실행한 뒤 권한을 RemoteSigned로 바꿔준다.

 

3. tsconfig.json 파일 생성

tsc --init 명령어로 tsconfig.json 파일을 만든 뒤에 다음과 같이 작성한다. 옵션을 꼭 따라할 필요는 없다.

{
  "compileOnSave": true,
  "compilerOptions": {
    "target": "es2016",
    "jsx": "react-jsx",
    "module": "esnext",
    "sourceMap": true,
    "removeComments": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "allowSyntheticDefaultImports": true,
    "noFallthroughCasesInSwitch": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": false
  },
  "include": [
    "./src/*"
  ],
  "exclude": [
    "node_modules/*"
  ]
}

 

4. webpack.config.js

const path = require('path');

module.exports = {
  entry: './src/index.ts',
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
    ],
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
  },
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
};

기존 webpack 파일에 필요한 부분을 채워넣어준다.

 

혹시 기존에 babel 을 사용하고 있었다면 .babelrc 파일에 아래를 추가하고

"preset" : ["@babel/preset-typescript"]

webpack 파일에 다음을 추가해주자.

      {
        test: /\.(ts|js)x?$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
        },
      },

 

4. 컴파일

$ tsc

 

혹시 컴파일 시 결과를 터미널에서 알고 싶을 때는 tsconfig.json 폴더에서 noemit 부분을 false로 바꿔준다.

컴파일 하고 Cannot write file '경로' because it would overwrite input file.

이런 에러가 뜬다면

{
  "compilerOptions": {
    "outDir": "build",
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "build/**/*"]
}

outDir 폴더를 만들어주고, exclude 시켜준다.

 

tsc 명령어로 에러가 안뜬다면 webpack을 실행해준다.

$ npx webpack

 

참고로 tsc 다음에 파일 명을 쓴다면 tsconfig.json이 안먹힌다!

5. can only be default-imported using the 'esModuleInterop' flag

위와 같은 에러가 뜬다면 tsconfig.json 파일에 "esModuleInterop": true, 속성을 추가해주자.

기존 CommonJS 모듈을 ES6모듈 사양을 준수하여 가져올 수 있게 된다.

728x90
반응형

+ Recent posts