简体   繁体   中英

Typescript AMD Module not returning anything

I am exporting a simple function inside of a "log.ts" file:

export function message(s : string) {
    console.log(s);
}

This is imported by a file ("MyController.ts") in the same directory:

import log = module("./log");
class MyController {

    a : string = "aaa";

    constructor () {
        log.message("hello world");
    }
}

When compiled, I get the following JS:

define(["require", "exports", "./log"], function(require, exports, __log__) {
    var log = __log__;

    var MyController = (function () {
        function MyController() {
            this.a = "aaa";
            log.message("hello world");
        }
        return MyController;
    })();    
})
//@ sourceMappingURL=MyController.js.map

This define function should return MyController. Because it does not, the callback inside this snippet does not get anything for the controller parameter:

   require(["MyController"], function (controller) {
                    theRoute.controller = controller;
                    defer.resolve();
                    $rootScope.$apply();
                });

I can fix this by manually adding the return inside of the call to define, but this is not a good workaround because the JS is being outputted by the TS compiler.

Am I doing something wrong or is this a bug in typescript?

You should write:

import log = module("./log");
export class MyController { // <--- 'export'
    a : string = "aaa";
    constructor () {
        log.message("hello world");
    }
}

And:

   require(["MyController"], function (controller) {
     theRoute.controller = new controller.MyController(); // <--
     defer.resolve();
     $rootScope.$apply();
   });

Starting in 0.9.x you'll be able to write export = MyController; at the bottom of the .ts file to make the class be the top-level exported object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM