TypeScript compile AMD modules with required defin

2019-03-19 12:45发布

问题:

In AMD (as implemented in requirejs) one can defined modules to be included as dependencies, eg:

define(['require','exports'], function(require, exports) {
  var externalDep = require('path/to/depModule');

  // Use the module somewhere.
});

I have tried the --module amd and it outputs correctly an AMD module usable by requirejs.

Is it possible to define dependencies inside the source of TypeScript source file that translates to something like the example above?

回答1:

You need to "export" your modules;

export module depModule { 
    export class A { 
    }
}

that will transalate into JavaScript code that looks like:

define(["require", "exports"], function(require, exports) {
    (function (depModule) {
        var A = (function () {
            function A() { }
            return A;
        })();
        depModule.A = A;
    })(exports.depModule || (exports.depModule = {}));
})

and then you consume them by using "import":

module otherModule { 
    import  depModule = module('depModule');
    var a = new depModule.depModule.A();
}

you will need to specify the type of your module code generation to the compiler using --module AMD.