2017-01-12 1 views
3

utility.ts브라우저에서 타이프 스크립트를 사용하는 방법은 무엇입니까?

let books = [ 
    { id: 1, title: "the dark window", author: "krishna", available: true }, 
    { id: 2, title: "naked eye", author: "sydney", available: false }, 
    { id: 3, title: "half girlfriend", author: "chetan", available: true }, 
    { id: 4, title: "make my dreams", author: "salam", available: false } 
]; 

export { books }; 

main-는

import {books} from './utility'; 

let getAllBooks =(): void => { 
    books.filter((val) => { 
     console.log(val.author); 
    }) 
} 

가 어떻게 HTML 페이지에 getAllBooks의 functiion에 액세스 할 수 있습니다 app.ts? 수출 및 가져 오기를 사용하지 않으면 완벽하게 작동하지만 모든 것을 하나의 파일에 쓰는 대신이 파일을 사용해야합니다.

출력 [main.js]로 하나의 JS 파일을 생성하려면 [amd module 사용]에 대한 조언을 구하십시오. Chrome 콘솔에서 아래 오류가 표시됩니다.

[(지수) 13 catch되지는 ReferenceError : getAllBooks은 HTMLInputElement.onclick ((지수) 13)에 정의되지]

내 HTML 페이지

<html> 
<title>Welcome</title> 

<head> 
    <script data-main="./js/main" src="./js/require.js"></script> 
    <script src="./js/main.js"></script> 

    <body> 
     <div id="mytest"></div> 
     <input type="button" value="Click!" id="btnClick" onclick="getAllBooks();" /> 


     <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> 
    </body> 
</head> 

</html> 

main.js

define("utility", ["require", "exports"], function (require, exports) { 
    "use strict"; 
    let books = [ 
     { id: 1, title: "the dark window", author: "krishna", available: true }, 
     { id: 2, title: "naked eye", author: "sydney", available: false }, 
     { id: 3, title: "half girlfriend", author: "chetan", available: true }, 
     { id: 4, title: "make my dreams", author: "salam", available: false } 
    ]; 
    exports.books = books; 
}); 
define("app", ["require", "exports", "utility"], function (require, exports, utility_1) { 
    "use strict"; 
    let getAllBooks =() => { 
     utility_1.books.filter((val) => { 
      console.log(val.author); 
     }); 
    }; 
}); 
//# sourceMappingURL=main.js.map 
+0

콘텐츠 출력 main.js 파일을 표시 할 수 있습니까? –

+0

모듈 로더를 HTML에서 직접 정의하는 것은 다소 나쁜 아이디어라고 생각합니다 ... – Sirko

+0

@ Hjort-e main.js 파일을 포함했습니다. – KrishOnline

답변

-2

typescript 컴파일러를 사용하여 .ts 파일을 .js 파일로 컴파일 한 다음 페이지에 포함 할 수 있습니다. 이 같은

뭔가 : HTML 파일에서

typescript my-file.ts 

:

<html> 
    <head> 
    </head> 
    <body> 
    <script src="my-file.js"></script> 
    </body> 
</html> 
+1

질문이 이미 답변과 동일하기 때문에 Downvoted –

+1

나는 이미 이러한 단계를 수행하여 하나의 자바 스크립트 파일로 만들었습니다. – KrishOnline

0

브라우저가 아직 자바 스크립트 모듈을 지원하지 않습니다. 개발자가 될 때까지 개발 워크 플로우에 browserify를 포함시켜야합니다. Browserify는 모듈을 브라우저 친화적 인 번들로 연결합니다.

Browserify는 입력 스크립트 워크 플로우에서 작업하는 것이 매우 간단합니다. 모험을 느끼는 경우 WebPack, Rollup 또는 SystemJs와 같은 다른 번들을 볼 수 있습니다.

참고 : 이것은 TypeScript에만 해당되지 않습니다. 현대 자바 스크립트 (es6 또는 CommonJS 모듈)를 개발할 때 브라우저 용 모듈을 번들로 제공해야합니다.

+1

질문에있는 예제가 이미 모듈 로더, 즉 require.js를 사용하고 있기 때문에 Downvoted. –

+1

@Martin browserify를 사용하여 예제를 제공해 주시겠습니까? – KrishOnline

관련 문제