Splitting large typescript file into module across multiple files

前端 未结 1 1801
孤城傲影
孤城傲影 2021-02-07 10:36

I currently have a large typescript file that I want to split up. There are a few functions and variables only used within the file, and a number of classes. It currently looks

1条回答
  •  天涯浪人
    2021-02-07 11:34

    I would suggest you move to the ES6 style of modules & imports. Instead of what is now called "namespaces" using the keyword module.

    To adapt your example above do this...

    //Widget.ts
    export class Widget { ... }
    
    //Section.ts
    export class Section { ... }
    
    //ReportTemplate.ts
    import {Widget} from './Widget.ts';
    import {Section} from './Section.ts';
    var numbers = [1, 2, 3];
    function formatDate() { ... }
    function doStuff() {
      // use the classes you imported
      var widget = new Widget();
      var section = new Section();
    }
    

    You will have to tell tsc what module syntax to use, and target at least ES5:

    //tsconfig.json
    {
      "module": "common",
      "target": "ES5"
    }
    

    There was conversation regarding this change when it when into TypeScript here

    0 讨论(0)
提交回复
热议问题