How can I define dependent modules in TypeScript AMD Modules

后端 未结 2 1717
眼角桃花
眼角桃花 2021-02-04 18:34

How can I define the dependent modules in a AMD Module with TypeScript, including, for instance, jQuery and underscore. Using JavaScript I do, for example, like this:

         


        
2条回答
  •  -上瘾入骨i
    2021-02-04 19:17

    This currently does not work correctly in typescript due to a bug in the compiler (see stackoverflow). What you would need to do is define a module moduleA that imports jquery and underscore, and then compile that with -module amd. Basically, you would need the following three files:

    moduleA.ts

    export module moduleA {
        import jquery = module("jquery");
        import underscore = module("underscore");
        console.log(jquery.jquery);
        console.log(underscore.underscore);
    }
    

    jquery.ts

    export module jquery {
        var jquery = "jquery";
    }
    

    underscore.ts

    export module underscore {
        var underscore = "underscore";
    }
    

    Compiling those three files with tsc -module amd yields the following code for moduleA.js:

    define(["require", "exports"], function(require, exports) {
        (function (moduleA) {
            var jquery = __jquery__;
    
            var underscore = __underscore__;
    
            console.log(jquery.jquery);
            console.log(underscore.underscore);
        })(exports.moduleA || (exports.moduleA = {}));
    
    })
    

    Like I said above, due to a bug in the compiler, this code is actually incorrect and will complain about missing __jquery__ at runtime. However, once this bug is fixed the amd loader of node.js should be able to load the modules.

提交回复
热议问题