본문 바로가기
프로그래밍/gulp.js

gulp - Typescript 컴파일 하기

by dryadyou 2021. 1. 24.
반응형


목차

1. gulp - babel을 이용하여 개발 환경설정
2. gulp - Javascript를 babel을 이용하여 컴파일하기
3. gulp - Uglify를 이용하여 babel로 컴파일된 javascript 파일 축소하기
4. gulp - Node + TypeScript 컴파일하기
5. gulp - uglify를 이용하여 컴파일된 typescript 파일 축소하기(minify)


오늘은 node.js를 typescript를 이용하여 작성하는 방법을 알아보겠다.
기본적인 gulp개발환경설정은 이전포스트에서 확인 할 수 있다.

typescript 모듈 설치

$ yarn add typescript gulp gulp-typescript -D

typescript 예제파일 작성

  • src/components 폴더안에 utils.ts 파일을 생성한다.
const hello = (message: string): void => console.log(`hello ${message}`)

export default hello
  • src폴더안에 index.ts 파일을 생성한다.
import hello from './components/utils'

function aplus(a: number, b: number): void {
  console.log(a + b)
}
hello('typescript')
aplus(1, 2)

root디렉토리에 tsconfig.json파일 생성

{
  "include": ["src"],
  "compilerOptions": {
    "noImplicitAny": true,
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "baseUrl": ".",
    "paths": {
      "*": ["node_modules/*", "src/types/*"]
    },
    "strict": true /* Enable all strict type-checking options. */,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true
  }
}

gulpfile.babel.js 파일 작성

import gulp from 'gulp'
import ts from 'gulp-typescript'
const tsProject = ts.createProject('tsconfig.json')

const routes = {
  typescript: {
    dest: 'build',
  },
}

const typescript = () =>
  tsProject
    .src()
    .pipe(tsProject())
    .js.pipe(gulp.dest(routes.typescript.dest))

export const dev = gulp.series(typescript)

gulp 실행

  1. gulp를 실행하면 아래와 같이 js가 먼저 실행된 후 typescript가 정상적으로 실행된걸 확인 할 수 있다.
$ yarn dev
yarn run v1.21.0
$ gulp dev
[07:07:28] Requiring external module @babel/register
[07:07:29] Using gulpfile D:\workspace\dryadsoft\gulp\gulp_typescript\gulpfile.babel.js
[07:07:29] Starting 'dev'...
[07:07:29] Starting 'typescript'...
[07:07:31] Finished 'typescript' after 1.44 s
[07:07:31] Finished 'dev' after 1.45 s
Done in 3.38s.
  • 실행결과 root디렉토리의 지정한 build폴더에 컴파일된 파일이 아래와 같이 node에서 실행할 수 있는 js파일로 변환되어 생성된다.
// utils.ts -> utils.js
'use strict'
Object.defineProperty(exports, '__esModule', { value: true })
var hello = function(message) {
  return console.log('hello ' + message)
}
exports.default = hello
// index.ts -> index.js
'use strict'
Object.defineProperty(exports, '__esModule', { value: true })
var tsUtil_1 = require('./tsUtil')
function aplus(a, b) {
  console.log(a + b)
}
tsUtil_1.default('typescript')
aplus(1, 2)

node 실행하기

  • 실행은 index.ts파일이 아닌 컴파일되어 생성된 index.js파일을 실행한다.
$ node build/index.js
hello typescript
3
반응형

댓글