Typescript

Raphael Click 및 Mouse Over Event Test

6월 12, 2017 Typescript No comments

Raphael을 사용하여 Circle 그리기

for(var i=0; i<10; i++) 
{ 
    paper = Raphael(0, 0, 500, 500); 
    var circle = paper.circle(50, i*50, width); 
}

출력화면

circle_1

여기서 circle에 click 및 mouse over event 연동 추가


    circle .click(function(this : any){
        this.attr({fill : '#0F0'});
    })

    circle.mouseover(function(this : any){  
        this.attr({fill : '#F00'});
    })

이때, 문제 발생

  1. Mouse Click 및 Over Event가 Random하게 인식되는 현상.
  2. 한번 전체적으로 Mouse Over를 통해 인식된 이후 부터는 정상 인식되는 현상

원인 ㅡㅡ;

최초 circle의 attribute가 없어서 line으로만 인식,,,…..ㅡㅡ;;;

최초 circle 생성시

attr({fill : '#000'})

추가 후 정상적으로 잘 작동 됨

‘this’ implicitly has type ‘any’ because it does not have a type annotation.

6월 12, 2017 Typescript No comments

‘this’ implicitly has type ‘any’ because it does not have a type annotation.

raphael의 element에 click시 event 연동 구현시 위와 같은 error 발생

click시 event 구현 code는 아래 처럼

this.ele.click(function(){
    console.log("test click::x=%d, y=%d", x, y);
    this.attr({fill : '#0F0'});
})

click event 첫번째 parameter로 element를 전달하기에 this를 any로 명시 필요


this.ele.click(function(this : any){
    console.log("test click::x=%d, y=%d", x, y);
    this.attr({fill : '#0F0'});
})

위와 같이 수정 후 해결

Webpack 수행시 ‘Module not found : Error : Can’t resolve …’ error

6월 7, 2017 Typescript No comments

Typesciprt class를 Import시 ‘Module not found : Error…’ 발생 해결

  1. 아래와 같은 DSButton이라는 class를 export
    export class DSButton {
        x : number = 0;
        y : number = 0;
        width : number = 0;
        height : number = 0;
    
        constructor(x:number, y:number, width:number, height:number){
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
        }
    
        ToString() {
            return "x=" + this.x + ", y=" + this.y + ", width=" + this.width + ", height=" + this.height;
        }
    }
    
  2. app.ts에서 DSButton을 사용하는 sample 작성
    import { DSButton } from './DSButton'
    
    let button : DSButton;
    button = new DSButton(0, 0, 100, 200);
    console.log('button.ToString()=' + button.ToString()); 
    
  3. webpack.config.json에 entry를 app.ts로 설정 하고 awesome-typescript-loader를 설정
    module.exports = {
      entry: './app.ts',
      output: {
        path: __dirname + '/build',
        filename: 'bundle.js'
      },
    
      module: {
            loaders: [
                // 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" }
            ]
      }          
    };
    
  4. webpack을 bundle수행시 DSButton module을 찾을 수 없다는 Error 발생webpack_error
  5. webpack.config.json 파일에 resolve : extensions:['.ts'] 추가
    resolve: {
        extensions: ['.ts']
      }
    
  6. 정상 bundle 및 정상 출력 됨

외부 Javascript module 사용

6월 1, 2017 Typescript No comments

Typescript를 시작하고, 처음부터 맨붕이 왔던것은 Javascript에서 module 방식을 지원하지 않다보니, 그에 대한 대체 수단에 대한 개념 잡기가 쉽지 않음

외부 Javascript Module 사용

  1. Raphael JS (http://dmitrybaranovskiy.github.io/raphael) 를 Typescript에서 사용하여 원 그리기 예제 시작
  2. npm을 통해 Raphael JS 설치 하기
    $ npm install --save raphael
    
  3. test_raphael.ts source 상단에 raphael module Import 추가Javascript library를 직접 사용하려고 하기에 npm에서 설치된 경로의 .js 파일을 직접 입력
    import raphael = require('./node_modules/raphael/raphael.js');
    
  4. 간단한 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
    });
    
  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.
    
  6. .ts source 폴더와 output .js 폴더가 동일해서 발생…;; 단지 tsconfig.json에서 "outDir" : "build"로 변경 시 정상 수행 됨
  7. 해당 test_raphael.js source를 index.html에 포함한후 apache server에서 구동시 raphael not define이라는 error가 발생 됨 이는 raphael.js 파일을 Front End단에서는 찾을 수가 없기에 발생
    그렇기에 bundle 형태로 관련 javascript파일을 자동으로 뭉쳐주는 webpack을 사용하여 packaging 해주어야 함.
  8. 당연히 npm을 사용하여 webpack을 설치. 원하는 데이터 형태를 bundle해 줄수 있는 loader를 선택하여 설치 Typescript는 awesome-typescript-loader, source-map-loader를 설치
    $npm install --save webpack awesome-typescript-loader source-map-loader
    
  9. 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" }
            ]
      },
    };
    
  10. webpack을 실행하여 bundle 수행
    $webpack
    

    참고로 webpack –watch 수행시 source가 변경시 자동 build됨

  11. index.html 생성 webpack을 통해 최종 build된 bundle.js를 포함
      &lt;html&gt;
            &lt;head&gt;
            &lt;/head&gt;
    
            &lt;body&gt;
                &lt;script type="text/javascript" src="bundle.js"&gt;
                &lt;/script&gt;
    
                Test raphael.js
            &lt;/body&gt;
        &lt;/html&gt;
    
  12. 결과 화면
    output_raphael

Typescript 환경 구축

5월 31, 2017 Typescript No comments

Typescript 최초 시작

  1. npm을 통해서 typescript설치 (tsd도 같이 설치 : TypeScript Definition Manager)

    c:\Test&gt;npm install -g typescript tsd
    
  2. greeter.ts라는 typescript source file생성

    function greeter(person : string){
        return "Hello, " + person;
    }
    var user = 123;
    document.body.innerHTML = greeter(user);
    
  3. 확장자 ts를 tsc를 이용하여 compile

    c:\test&gt;tsc greeter.ts
    
  4. 최종 js 파일로 결과 출력

npm init을 통한 package 초기화 수행

$npm init
  • 자동으로 package.json 파일 생성 그 이후

    $npm install –save typescript

package.json 샘플

{
  "name": "typescript_test",
  "version": "1.0.0",
  "description": "test",
  "main": "index.html",
  "scripts": {
    "build": "echo build",
    "start": "echo test",
    "test": "echo \"Error: no test specified\" &amp;&amp; exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/scanhand/TypeScript_Test.git"
  },
  "author": "scanhand",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/scanhand/TypeScript_Test/issues"
  },
  "homepage": "https://github.com/scanhand/TypeScript_Test#readme",
  "dependencies": {
    "raphael": "^2.2.7",
    "tsd": "^0.6.5",
    "typescript": "^2.3.3"
  }
}

위와같이 –save를 설정시 package.json 파일에 자동 저장됨

typescript 초기화

$ tsc --init

수행시 자동으로 tsconfig.json 파일 생성됨

    {
      "compilerOptions": {
        /* Basic Options */                       
        "target": "es5",                          /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */
        "module": "commonjs",                     /* Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'. */    
        "allowJs": true,                       /* Allow javascript files to be compiled. */    
        "sourceMap": true,                     /* Generates corresponding '.map' file. */    
        "outDir": "build",                        /* Redirect output structure to the directory. */          
        /* Strict Type-Checking Options */        
        "strict": true                            /* Enable all strict type-checking options. */

      },
      "files" : [
        "test_raphael.ts"
      ]
    }

Typescript 시작

5월 31, 2017 Typescript No comments

항상 web application을 해야지 생각만 했었는데 지금 부터 맨땅에 해딩하기 시작 함. (앞으로 post는 순서 및 내용이 뒤죽박죽 할 예정)

  • AngularJs에서도 사용하고, Microsoft에서도 밀고 있는 Typescript로 접근해 보기 시작.

  • 처음 작업환경은 Local Computer에서 npm을 이용해서 환경 설정하고 작업 하기 시작.

  • 하지만, 작업 computer가 바뀌는 경우, 특히 집과 회사를 오가면서 같은 작업 반복시 github만 가지고는 조금 애매해 지기 시작함

  • 그러다 우연히 찾은 c9(https://c9.io)을 작업 환경으로 사용하기 시작

  • 작업 환경이 SublimeText와 느낌이 비슷하고, linux shell도 제공해주고, 무엇보다 virtual machine을 활용하여, 나만의 작업 환경을 그대로 유지하는게 참 좋음 (특히 무료!!!)

c9_ui