How do I import other TypeScript files?

前端 未结 9 1592
北恋
北恋 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 21:00

    I would avoid now using /// but for external libraries where the definition file is not included into the package.

    The reference path solves errors in the editor, but it does not really means the file needs to be imported. Therefore if you are using a gulp workflow or JSPM, those might try to compile separately each file instead of tsc -out to one file.

    From Typescript 1.5

    Just prefix what you want to export at the file level (root scope)

    aLib.ts

    {
    export class AClass(){} // exported i.e. will be available for import
    export valueZero = 0; // will be available for import
    }
    

    You can also add later in the end of the file what you want to export

    {
    class AClass(){} // not exported yet
    valueZero = 0; // not exported yet
    valueOne = 1; // not exported (and will not in this example)
    
    export {AClass, valueZero} // pick the one you want to export
    }
    

    Or even mix both together

    {
    class AClass(){} // not exported yet
    export valueZero = 0; // will be available for import
    export {AClass} // add AClass to the export list
    }
    

    For the import you have 2 options, first you pick again what you want (one by one)

    anotherFile.ts

    {
    import {AClass} from "./aLib.ts"; // you import only AClass
    var test = new AClass();
    }
    

    Or the whole exports

    {
    import * as lib from "./aLib.ts"; // you import all the exported values within a "lib" object
    var test = new lib.AClass();
    }
    

    Note regarding the exports: exporting twice the same value will raise an error { export valueZero = 0; export {valueZero}; // valueZero is already exported… }

提交回复
热议问题