26

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
3
  • Could you show us the content output main.js file? Commented Jan 12, 2017 at 19:15
  • I think mixing a module loader an the definition of events directly in HTML is a rather bad idea ... Commented Jan 12, 2017 at 19:18
  • @Hjort-e I have included the main.js file Commented Jan 15, 2017 at 8:29

4 Answers 4

17
  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.

Sign up to request clarification or add additional context in comments.

Comments

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.

6 Comments

Downvoted, because the example in the question uses a module loader already, namely require.js.
@Martin Can you please provide an example using browserify?
Not really true. Pretty sure Chrome supports es6 modules.
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.
Is this still true in 2021?
|
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/

1 Comment

The link is not working
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.