如何在浏览器中使用打字稿? [英] How to use typescript in browser?
问题描述
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
main- app.ts
import {books} from './utility';
let getAllBooks = (): void => {
books.filter((val) => {
console.log(val.author);
})
}
如何访问 Html 页面中的 getAllBooks 功能?如果我不使用导出和导入,它可以正常工作,但我必须使用它而不是将所有内容都写入一个文件中.
How can I access the getAllBooks functiion in a Html page? If I don't use export and import it works perfectly fine but I have to use it instead of writing everything into one file.
请建议[使用amd模块]生成一个JS文件作为输出[main.js].在 chrome 控制台中出现以下错误.
Please advice [using amd module] to generate one JS file as output [main.js]. Getting the below error in the chrome console.
[(index):13 Uncaught ReferenceError: getAllBooks 未定义在 HTMLInputElement.onclick ((index):13)]
[(index):13 Uncaught ReferenceError: getAllBooks is not defined at 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
推荐答案
- 将浏览器更新到最近的浏览器(最近足以支持 ES2015 模块)
- 将 tsconfig.json
target
更改为es2015
- 将 tsconfig.json
module
更改为es2015
- 始终在导入语句中添加 .js 扩展名
- 使用像 live-server 这样的 http 服务器来避免使用 file://协议的 CORS 问题
- Update browser to recent one (recent enough to support ES2015 module)
- Change tsconfig.json
target
toes2015
- Change tsconfig.json
module
toes2015
- Always add .js extension to your import statements
- Use an http server like live-server to avoir CORS concerns with file:// protocol
奖励: 将 tsconfig.json moduleResolution
显式设置为 node
.如果您不使用外部库或 @types/* 包,则不需要这样做.
BONUS: Explicitly set tsconfig.json moduleResolution
to node
. This is not necessary if you don’t use external libraries or @types/* packages.
在以下位置完全查看:https://github.com/SalathielGenese/ts-web
披露:我是它的作者.
这篇关于如何在浏览器中使用打字稿?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!