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 };
主要应用程序
import {books} from './utility';
let getAllBooks = (): void => {
books.filter((val) => {
console.log(val.author);
})
}
如何在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>
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
target
更改为es2015
module
更改为es2015
奖励:明确将tsconfig.json moduleResolution
设置为node
。如果不使用外部库或@ types / *包,则不需要这样做。
在以下网址查看:https://github.com/SalathielGenese/ts-web
披露:我是它的作者。
浏览器还不支持javascript模块。在他们这样做之前,您需要将browserify包含在您的开发工作流程中。 Browserify将您的模块连接到浏览器友好的包中。
Browserify很容易在打字稿工作流程中工作。如果您喜欢冒险,可以查看其他捆绑包,如WebPack,Rollup或SystemJs。
请注意,这不是TypeScript特有的。在开发任何现代javascript(es6或CommonJS modukes)时,您需要为浏览器捆绑模块。
我是AMD的新手,但看起来你只定义模块,从不调用/导入它们到站点范围。在本教程中,作者有一个bootstrapping文件,作为应用程序的入口点,似乎是你所缺少的:http://www.codebelt.com/typescript/typescript-amd-with-requirejs-tutorial/
我认为标题是不正确的,你真正想要做的是在浏览器中运行TypeScript应用程序,这完全不同于“在浏览器中运行TypeScript,对吧?
在这种情况下,为了开始使用TypeScript,我建议你不要使用require.js添加类似捆绑器的工具,如parcel,webpack,browserify,rollup等工具。 parcel非常简单:对于你的例子,1)删除所有脚本标签并仅添加以下内容:<script src="my/app.ts">
然后用parcel theFile.html
“编译”该html或为生产构建:parcel build theFile.html
如果我是对的,你能不能更改这个问题的标题,因为这是令人困惑和误导的?谢谢。
现在,另一方面,如果你真的想要运行TypeScript作为标题说,typescript与浏览器完全兼容(.js文件库是node_modules / typescript / lib / typescript.js)。只需将其作为另一个模块导入或将文件加载到脚本标记中并使用编译器API。
这个项目包含我对该主题的研究,包括几个工作示例和演示应用程序以及一些工具:https://github.com/cancerberoSgx/typescript-in-the-browser
您可以使用typescript编译器将.ts
文件编译为.js
文件,然后将其包含在您的页面中。
像这样的东西:
typescript my-file.ts
在你的html文件中:
<html>
<head>
</head>
<body>
<script src="my-file.js"></script>
</body>
</html>