B Adams
B Adams

Reputation: 87

How to access exported TypeScript class from JavaScript using AMD and RequireJS

I have the following TypeScript class in the file: bar.ts

export class Bar {
   log(message:string):void {
       console.log(message);
   }
}

In the file foo.ts I have:

import { Bar } from "bar";

window.onload = () => {
   var foo = new Bar();
   foo.log("Hello World");
};

I am compiling with:

lib: ["dom", "es2015.promise", "es2015"]
module: "amd"
declarationFiles: true
target: "ES5"
noImplicitAny: true
out: "test.js

How can I instantiate the Bar class? The window.onload event is not called. The following is the generated code:

define("bar", ["require", "exports"], function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var Bar = (function () {
        function Bar() {
        }
        Bar.prototype.log = function (message) {
            console.log(message);
        };
        return Bar;
    }());
    exports.Bar = Bar;
});

define("foo", ["require", "exports", "bar"], function (require, exports, bar_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    window.onload = function () {
        var foo = new bar_1.Bar();
        foo.log("Hello World");
    };
});

Is there a way to reference Bar from standard JavaScript? I have included require.js in the HTML page and there are no JavaScript errors when the page loads.

This is a simplified version of the problem but I need to use export as the project has many classes each stored in separate files and I need to combine them into a single file.

Upvotes: 2

Views: 975

Answers (1)

amiramw
amiramw

Reputation: 506

You should be able to reference Bar from regular javascript. Try to do it from the requirejs data-main script.

In the HTML:

<script data-main="scripts/main" src="scripts/require.js"></script>

In scripts/main:

requirejs(["bar"], function(bar) {});

Upvotes: 1

Related Questions