網站搜尋

node.js - 如何在瀏覽器中使用 TypeScript?


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- app.ts

import {books} from './utility';

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

我如何在 HTML 頁面中訪問 getAllBooks 函數?如果我不使用 export 和 import,它運作得非常好,但我必須使用它,而不是將所有內容寫入一個文件中。

請建議[使用 AMD 模組]生成一個 JS 檔作為輸出[main.js]。在 Chrome 控制台中出現以下錯誤。

[(index):13 未捕獲的 ReferenceError:getAllBooks 未定義 在 HTMLInputElement.onclick ((index):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

答案#1

  1. 將瀏覽器更新到較新的版本(新到足以支援 ES2015 模組)
  2. 將 tsconfig.json 的 target 改為 es2015
  3. 將 tsconfig.json 的 module 改為 es2015
  4. 在你的匯入語句中始終添加 .js 擴展名
  5. 使用像 live-server 這樣的 HTTP 伺服器來避免 file:// 協議的 CORS 問題

獎勵: 明確地將 tsconfig.json 的 moduleResolution 設置為 node。如果您不使用外部庫或 @types/* 套件,這不是必要的。

完整查看請訪問: https://github.com/SalathielGenese/ts-web

揭露:我是它的作者。

答案#2

瀏覽器尚不支援 JavaScript 模組。在它們支援之前,你需要將 Browserify 納入你的開發工作流程。Browserify 將你的模組合併成適合瀏覽器使用的捆綁檔案。

在 TypeScript 工作流程中,Browserify 非常容易上手。如果你想嘗試冒險,可以看看其他打包工具,如 WebPack、Rollup 或 SystemJs。

注意,這並非特定於 TypeScript。在開發任何現代 JavaScript(ES6 或 CommonJS 模組)時,你都需要為瀏覽器打包模組。