How do I import other TypeScript files?

前端 未结 9 1633
北恋
北恋 2020-11-28 20:29

When using the TypeScript plugin for vs.net, how do I make one TypeScript file import modules declared in other TypeScript files?

file 1:

module moo
         


        
9条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 20:59

    Typescript distinguishes two different kinds of modules: Internal modules are used to structure your code internally. At compile-time, you have to bring internal modules into scope using reference paths:

    /// 
    
    class bar extends moo.foo {
    }
    

    On the other hand, external modules are used to refernence external source files that are to be loaded at runtime using CommonJS or AMD. In your case, to use external module loading you have to do the following:

    moo.ts

    export class foo {
        test: number;
    } 
    

    app.ts

    import moo = module('moo');
    class bar extends moo.foo {
      test2: number;
    }
    

    Note the different way of brining the code into scope. With external modules, you have to use module with the name of the source file that contains the module definition. If you want to use AMD modules, you have to call the compiler as follows:

    tsc --module amd app.ts
    

    This then gets compiled to

    var __extends = this.__extends || function (d, b) {
        function __() { this.constructor = d; }
        __.prototype = b.prototype;
        d.prototype = new __();
    }
    define(["require", "exports", 'moo'], function(require, exports, __moo__) {
        var moo = __moo__;
    
        var bar = (function (_super) {
            __extends(bar, _super);
            function bar() {
                _super.apply(this, arguments);
    
            }
            return bar;
        })(moo.foo);
    })    
    

提交回复
热议问题