Using namespace spread over multiple module files in TypeScript

后端 未结 5 925

I\'ve started work on a large-scale typescript project.

Right from the outset, I want to keep my files organized (this project will be split between lots of developers

5条回答
  •  余生分开走
    2021-01-31 08:52

    External modules imply that you load modules file by file. Both AMD and CommonJS do not have such thing as namespace. You can use some kind of postprocessing to bundle files in one module.


    The following defines an internal module:

    module Animals {
        export class Reptiles {
            constructor() {
            }
        }
    }
    

    You shouldn't use import for it. Animals.Reptiles is visible anywhere. The only aim is to load scripts in the proper order (e.g. base classes before heritors). So you should list all files in ts.config or somewhere else. In my project I use bundles on folders and have a convention to add @ to filenames of base classes.

    Another solution is to use external modules: AMD (RequireJS) or CommonJS (Browserify). In that case remove upper level module from declaration. If one file contains only one type you can export it as a root:

    class Reptiles {
        constructor() {
        }
    }
    
    export = Reptiles;
    

    You can refer module by file path:

    import Reptilies = require('..\Animals\Reptilies')
    var  reptile = new Reptile();
    

    Or with new ES6 modules:

    export class Reptiles {
        constructor() {
        }
    }
    

    import { Reptiles } from '..\Animals\Reptilies';
    

提交回复
热议问题