Typescript를 시작하고, 처음부터 맨붕이 왔던것은 Javascript에서 module 방식을 지원하지 않다보니, 그에 대한 대체 수단에 대한 개념 잡기가 쉽지 않음
외부 Javascript Module 사용
Raphael JS
(http://dmitrybaranovskiy.github.io/raphael) 를 Typescript에서 사용하여 원 그리기 예제 시작- npm을 통해 Raphael JS 설치 하기
$ npm install --save raphael
test_raphael.ts
source 상단에 raphael module Import 추가Javascript library를 직접 사용하려고 하기에 npm에서 설치된 경로의 .js 파일을 직접 입력import raphael = require('./node_modules/raphael/raphael.js');
- 간단한 Circle을 그리는 source 추가
var paper = raphael(0, 0, 200, 200); var circle = paper.circle(100, 100, 50); circle.attr({ 'fill' : '#00f', 'stroke':'#000', 'stroke-width':5 });
- 테스트 삼아서 Typescript build 해보자. 안된다.~!!! ㅡㅡ; Build Error!!다행히 친절히 설명해 준다.
$ tsc -p . test_raphael.ts(1,26): error TS6143: Module './node_modules/raphael/raphael.js' was resolved to '/home/ubuntu/workspace/node_modules/raphael/raphael.js', but '--allowJs' is not set.
tsconfig.json
파일에 allowjs : true를 설정 해주고 다시 build시 또 Error!!$ tsc -p . error TS5055: Cannot write file '/home/ubuntu/workspace/node_modules/raphael/raphael.js' because it would overwrite input file.
- .ts source 폴더와 output .js 폴더가 동일해서 발생…;; 단지 tsconfig.json에서
"outDir" : "build"
로 변경 시 정상 수행 됨 - 해당 test_raphael.js source를 index.html에 포함한후 apache server에서 구동시 raphael not define이라는 error가 발생 됨 이는 raphael.js 파일을 Front End단에서는 찾을 수가 없기에 발생
그렇기에 bundle 형태로 관련 javascript파일을 자동으로 뭉쳐주는 webpack을 사용하여 packaging 해주어야 함. - 당연히 npm을 사용하여 webpack을 설치. 원하는 데이터 형태를 bundle해 줄수 있는
loader
를 선택하여 설치 Typescript는awesome-typescript-loader
,source-map-loader
를 설치$npm install --save webpack awesome-typescript-loader source-map-loader
- webpack.config.js 파일을 생성 하여 아래 code 추가
entry : Bundle을 시작할 시작 source file을 설정
output에 최종 bundle후 export되는 file 설정
module에 원하는 loader 설정module.exports = { entry: './test_raphael.ts', output: { path: __dirname, filename: 'bundle.js' }, module: { rules: [ // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'. { test: /\.tsx?$/, loader: "awesome-typescript-loader" }, // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'. { enforce: "pre", test: /\.js$/, loader: "source-map-loader" } ] }, };
- webpack을 실행하여 bundle 수행
$webpack
참고로 webpack –watch 수행시 source가 변경시 자동 build됨
- index.html 생성 webpack을 통해 최종 build된 bundle.js를 포함
<html> <head> </head> <body> <script type="text/javascript" src="bundle.js"> </script> Test raphael.js </body> </html>
- 결과 화면