如何在浏览器中使用打字稿?

Kri*_*ine 10 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 };
Run Code Online (Sandbox Code Playgroud)

主要应用程序

import {books} from './utility';

let getAllBooks = (): void => {
    books.filter((val) => {
        console.log(val.author);
    })
}
Run Code Online (Sandbox Code Playgroud)

如何在Html页面中访问getAllBooks功能?如果我不使用导出和导入它完全正常但我必须使用它而不是将所有内容写入一个文件.

请建议[使用amd模块]生成一个JS文件作为输出[main.js].在chrome控制台中获取以下错误.

[(index):13未捕获的ReferenceError:未在HTMLInputElement.onclick上定义getAllBooks((索引):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>
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

Sal*_*èse 11

  1. 将浏览器更新到最近的(最近足以支持 ES2015 模块)
  2. tsconfig.json 更改targetes2015
  3. tsconfig.json 更改modulees2015
  4. 始终在导入语句中添加.js扩展名
  5. 使用像 live-server 这样的 http 服务器来避免使用 file:// 协议的 CORS 问题

奖励 tsconfig.json显式设置moduleResolutionnode. 如果您不使用外部库或 @types/* 包,则这不是必需的。

在 : https://github.com/SalathielGenese/ts-web完全看到它

披露:我是它的作者。


Mar*_*tin 5

浏览器尚不支持 javascript 模块。在此之前,您需要将 browserify 包含到您的开发工作流程中。Browserify 将您的模块连接到浏览器友好的包中。

Browserify 在打字稿工作流程中工作非常简单。如果您喜欢冒险,可以查看其他捆绑器,例如 WebPack、Rollup 或 SystemJs。

请注意,这并非特定于 TypeScript。在开发任何现代 JavaScript(es6 或 CommonJS 模块)时,您将需要为浏览器捆绑模块。

  • 否决,因为问题中的示例已经使用了模块加载器,即 require.js。 (2认同)
  • @Martin 你能提供一个使用 browserify 的例子吗? (2认同)