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);
})
}
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.
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 is not defined at HTMLInputElement.onclick ((index):13)]
My html page
<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
You cannot use Typescript in Chrome. Typescript is superset of JS and you must first compile .
target
to es2015
module
to es2015
BONUS: Explicitly set tsconfig.json moduleResolution
to node
. This is not necessary if you don’t use external libraries or @types/* packages.
See it altogether at : https://github.com/SalathielGenese/ts-web
Disclosure : I'm its author.
Browsers do not yet support javascript modules. Until they do you will need to include browserify into your development workflow. Browserify concatenates your modules into a browser friendly bundle.
Browserify is very simple to get working in a typescript workflow. If you are feeling adventurous you can look at other bundlers like WebPack, Rollup or SystemJs.
Note, this is not specific to TypeScript. When developing any modern javascript (es6 or CommonJS modukes) you will need to bundle modules for the browser.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With