jquery만 쓰다가 typescript 한 번 따라하기 (2)
발만 담궈봅니다;
저는 몇년간 jquery만 쓰다가 어느날 갑자기 React로 개발을 하게 되었는데요, 그 때 무척 고생했었습니다. 그래서 한 번 typescript까지 소프트 랜딩을 할 수 있는 문서를 만들어보고 싶었습니다.
저도 배우는 입장이라 부족한 부분은 말씀해주시면 많이 감사합니다. 🥰
typescript는 이 문서와 공홈을 먼저 읽어주시고,
Playground에서 한 번 연습하고 오시는걸 전제로 시작해 보겠습니다.
이번 목표: typescript를 한 번 써보기
webpack loader 추가하기
webpack은 loader를 통해 여러 기능을 추가할 수 있습니다. 우리는 ts-loader
를 추가해서 webpack이 typescript를 javascript로 컴파일 할 수 있도록 해보겠습니다.
지난번에 하던 프로젝트에서 계속해 보겠습니다.
index.es5
를index.ts
로 rename 합니다.mymodule.es5
를mymodule.ts
로 rename 합니다.
그리고webpack.config.js
의entry
를 아래와 같이 수정해 줍니다.entry: { index: ‘./index.ts’ }
- typescript를 컴파일 할 수 있도록 패키지를 추가합니다.
yarn add typescript ts-loader
- webpack.config.js에 module을 추가해줍니다.
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
}
5. tsconfig.json
파일을 만들어 줍니다. 파일 내용은 비워둡니다.
6. 이제 아주 간단한 typescript 문법을 써볼까요?mymodule.ts
에 다음을 추가해 줍니다.
export function test2(): string {
return 'hello, world. this is mymodule.test2()';
}
7. 그리고 이걸 index.ts
에서 사용해 봅시다.
그 전에 첫 줄과 두번째 줄의 var를 import로 수정해 주세요.
두번째 줄의 mymodule.es5를 .ts로 수정해주세요.
import $ = require('jquery'); // var 대신 import를 사용합니다.
import mymodule = require('./mymodule.ts'); // 확장자가 수정 되었습니다.$(function () {
console.log('hello, world. this is index.js');
mymodule.test(); var test2: number = mymodule.test2();
console.log(test2);
});
이제 번들링과 컴파일을 해보고 결과를 확인해 봅시다.
yarn build
ERROR in /.../index.ts(8,7)
TS2322: Type 'string' is not assignable to type 'number'.
타입이 맞지 않아 에러가 발생합니다. mymodule.test2()
는 string
타입을 리턴하는데, var test2
는 number
타입이기 때문입니다.
var test2: string
으로 수정하고, 다시 yarn build
를 해봅시다.
hello, world. this is index.js
hello, world. this is mymodule.test()
hello, world. this is mymodule.test2()
확인이 잘 되셨을까요?
전체 코드는 아래에서 확인하실 수 있습니다.
https://github.com/eungook/webpack-test-02