25

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
KrishOnline
  • 488
  • 1
  • 5
  • 16

4 Answers4

15
  1. Update browser to recent one (recent enough to support ES2015 module)
  2. Change tsconfig.json target to es2015
  3. Change tsconfig.json module to es2015
  4. Always add .js extension to your import statements
  5. Use an http server like live-server to avoir CORS concerns with file:// protocol

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.

Salathiel Genese
  • 1,639
  • 2
  • 21
  • 37
5

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.

Martin
  • 15,820
  • 4
  • 47
  • 56
  • 2
    Downvoted, because the example in the question uses a module loader already, namely require.js. – Simon Meskens Jan 13 '17 at 23:28
  • 2
    @Martin Can you please provide an example using browserify? – KrishOnline Jan 15 '17 at 08:26
  • Not really true. Pretty sure Chrome supports es6 modules. –  Aug 12 '18 at 11:54
  • 1
    This answer was written Jan 12 2017, before Chrome supported ES6 modules. Infact this answer still holds up. If you are writing typescript for the web you should look long and hard at WebPack, or a tool that uses WebPack under the hood. – Martin Nov 29 '18 at 11:46
  • Is this still true in 2021? – user1461607 Mar 08 '21 at 16:03
  • Webpack, Parcel, Rollup, Esbuild, and others, are current options for creating web bundles for the web. TypeScript can be incorporated into the workflow. – Martin Dec 12 '22 at 16:25
0

Im new to AMD but it looks like you only define the modules, never invoke/import them to the sites scope. In this tutorial the author has a bootstrapping file that acts as entry point for an app which seems to be what you're missing: http://www.codebelt.com/typescript/typescript-amd-with-requirejs-tutorial/

Hjort-e
  • 315
  • 3
  • 9
0

I think the title is incorrect and what you really trying to do is running TypeScript applications in te browser which is totally different yo "Run TypeScript in the browser, right?

In that case to get started with TypeScript I recommend you to not use require.js add instead a bundler-like tool like a tool like parcel, webpack, browserify, rollup. parcel is super easy : For your example, 1) remove ALL script tags and add only the following: <script src="my/app.ts"> then "compile" that html with parcel theFile.html or build for production : parcel build theFile.html

if I was right, could you please change the title of this question since is confusing and misleading ? thanks.

Now, on the other side, If you really want to run TypeScript as the title say, typescript is fully compatible with the browser (the .js file library is node_modules/typescript/lib/typescript.js ). just import it as another module or load the file in a script tag and use the Compiler API..

This project contains my research on the topic with several working examples and demo apps and some tools: https://github.com/cancerberoSgx/typescript-in-the-browser

cancerbero
  • 6,799
  • 1
  • 32
  • 24