How do I use namespaces with TypeScript external modules?

前端 未结 9 1308
陌清茗
陌清茗 2020-11-22 08:59

I have some code:

baseTypes.ts

export namespace Living.Things {
  export class Animal {
    move() { /* ... */ }
  }
  export class          


        
相关标签:
9条回答
  • 2020-11-22 09:44

    Nothing wrong with Ryan's answer, but for people who came here looking for how to maintain a one-class-per-file structure while still using ES6 namespaces correctly please refer to this helpful resource from Microsoft.

    One thing that's unclear to me after reading the doc is: how to import the entire (merged) module with a single import.

    Edit Circling back to update this answer. A few approaches to namespacing emerge in TS.

    All module classes in one file.

    export namespace Shapes {
        export class Triangle {}
        export class Square {}      
    }
    

    Import files into namespace, and reassign

    import { Triangle as _Triangle } from './triangle';
    import { Square as _Square } from './square';
    
    export namespace Shapes {
      export const Triangle = _Triangle;
      export const Square = _Square;
    }
    

    Barrels

    // ./shapes/index.ts
    export { Triangle } from './triangle';
    export { Square } from './square';
    
    // in importing file:
    import * as Shapes from './shapes/index.ts';
    // by node module convention, you can ignore '/index.ts':
    import * as Shapes from './shapes';
    let myTriangle = new Shapes.Triangle();
    

    A final consideration. You could namespace each file

    // triangle.ts
    export namespace Shapes {
        export class Triangle {}
    }
    
    // square.ts
    export namespace Shapes {
        export class Square {}
    }
    

    But as one imports two classes from the same namespace, TS will complain there's a duplicate identifier. The only solution as this time is to then alias the namespace.

    import { Shapes } from './square';
    import { Shapes as _Shapes } from './triangle';
    
    // ugh
    let myTriangle = new _Shapes.Shapes.Triangle();
    

    This aliasing is absolutely abhorrent, so don't do it. You're better off with an approach above. Personally, I prefer the 'barrel'.

    0 讨论(0)
  • 2020-11-22 09:46

    Candy Cup Analogy

    Version 1: A cup for every candy

    Let's say you wrote some code like this:

    Mod1.ts

    export namespace A {
        export class Twix { ... }
    }
    

    Mod2.ts

    export namespace A {
        export class PeanutButterCup { ... }
    }
    

    Mod3.ts

    export namespace A {
         export class KitKat { ... }
    }
    

    You've created this setup:

    Each module (sheet of paper) gets its own cup named A. This is useless - you're not actually organizing your candy here, you're just adding an additional step (taking it out of the cup) between you and the treats.


    Version 2: One cup in the global scope

    If you weren't using modules, you might write code like this (note the lack of export declarations):

    global1.ts

    namespace A {
        export class Twix { ... }
    }
    

    global2.ts

    namespace A {
        export class PeanutButterCup { ... }
    }
    

    global3.ts

    namespace A {
         export class KitKat { ... }
    }
    

    This code creates a merged namespace A in the global scope:

    This setup is useful, but doesn't apply in the case of modules (because modules don't pollute the global scope).


    Version 3: Going cupless

    Going back to the original example, the cups A, A, and A aren't doing you any favors. Instead, you could write the code as:

    Mod1.ts

    export class Twix { ... }
    

    Mod2.ts

    export class PeanutButterCup { ... }
    

    Mod3.ts

    export class KitKat { ... }
    

    to create a picture that looks like this:

    Much better!

    Now, if you're still thinking about how much you really want to use namespace with your modules, read on...


    These Aren't the Concepts You're Looking For

    We need to go back to the origins of why namespaces exist in the first place and examine whether those reasons make sense for external modules.

    Organization: Namespaces are handy for grouping together logically-related objects and types. For example, in C#, you're going to find all the collection types in System.Collections. By organizing our types into hierarchical namespaces, we provide a good "discovery" experience for users of those types.

    Name Conflicts: Namespaces are important to avoid naming collisions. For example, you might have My.Application.Customer.AddForm and My.Application.Order.AddForm -- two types with the same name, but a different namespace. In a language where all identifiers exist in the same root scope and all assemblies load all types, it's critical to have everything be in a namespace.

    Do those reasons make sense in external modules?

    Organization: External modules are already present in a file system, necessarily. We have to resolve them by path and filename, so there's a logical organization scheme for us to use. We can have a /collections/generic/ folder with a list module in it.

    Name Conflicts: This doesn't apply at all in external modules. Within a module, there's no plausible reason to have two objects with the same name. From the consumption side, the consumer of any given module gets to pick the name that they will use to refer to the module, so accidental naming conflicts are impossible.


    Even if you don't believe that those reasons are adequately addressed by how modules work, the "solution" of trying to use namespaces in external modules doesn't even work.

    Boxes in Boxes in Boxes

    A story:

    Your friend Bob calls you up. "I have a great new organization scheme in my house", he says, "come check it out!". Neat, let's go see what Bob has come up with.

    You start in the kitchen and open up the pantry. There are 60 different boxes, each labelled "Pantry". You pick a box at random and open it. Inside is a single box labelled "Grains". You open up the "Grains" box and find a single box labelled "Pasta". You open the "Pasta" box and find a single box labelled "Penne". You open this box and find, as you expect, a bag of penne pasta.

    Slightly confused, you pick up an adjacent box, also labelled "Pantry". Inside is a single box, again labelled "Grains". You open up the "Grains" box and, again, find a single box labelled "Pasta". You open the "Pasta" box and find a single box, this one is labelled "Rigatoni". You open this box and find... a bag of rigatoni pasta.

    "It's great!" says Bob. "Everything is in a namespace!".

    "But Bob..." you reply. "Your organization scheme is useless. You have to open up a bunch of boxes to get to anything, and it's not actually any more convenient to find anything than if you had just put everything in one box instead of three. In fact, since your pantry is already sorted shelf-by-shelf, you don't need the boxes at all. Why not just set the pasta on the shelf and pick it up when you need it?"

    "You don't understand -- I need to make sure that no one else puts something that doesn't belong in the 'Pantry' namespace. And I've safely organized all my pasta into the Pantry.Grains.Pasta namespace so I can easily find it"

    Bob is a very confused man.

    Modules are Their Own Box

    You've probably had something similar happen in real life: You order a few things on Amazon, and each item shows up in its own box, with a smaller box inside, with your item wrapped in its own packaging. Even if the interior boxes are similar, the shipments are not usefully "combined".

    Going with the box analogy, the key observation is that external modules are their own box. It might be a very complex item with lots of functionality, but any given external module is its own box.


    Guidance for External Modules

    Now that we've figured out that we don't need to use 'namespaces', how should we organize our modules? Some guiding principles and examples follow.

    Export as close to top-level as possible

    • If you're only exporting a single class or function, use export default:

    MyClass.ts

    export default class SomeType {
      constructor() { ... }
    }
    

    MyFunc.ts

    function getThing() { return 'thing'; }
    export default getThing;
    

    Consumption

    import t from './MyClass';
    import f from './MyFunc';
    var x = new t();
    console.log(f());
    

    This is optimal for consumers. They can name your type whatever they want (t in this case) and don't have to do any extraneous dotting to find your objects.

    • If you're exporting multiple objects, put them all at top-level:

    MyThings.ts

    export class SomeType { ... }
    export function someFunc() { ... }
    

    Consumption

    import * as m from './MyThings';
    var x = new m.SomeType();
    var y = m.someFunc();
    
    • If you're exporting a large number of things, only then should you use the module/namespace keyword:

    MyLargeModule.ts

    export namespace Animals {
      export class Dog { ... }
      export class Cat { ... }
    }
    export namespace Plants {
      export class Tree { ... }
    }
    

    Consumption

    import { Animals, Plants} from './MyLargeModule';
    var x = new Animals.Dog();
    

    Red Flags

    All of the following are red flags for module structuring. Double-check that you're not trying to namespace your external modules if any of these apply to your files:

    • A file whose only top-level declaration is export module Foo { ... } (remove Foo and move everything 'up' a level)
    • A file that has a single export class or export function that isn't export default
    • Multiple files that have the same export module Foo { at top-level (don't think that these are going to combine into one Foo!)
    0 讨论(0)
  • 2020-11-22 09:48

    Try to organize by folder:

    baseTypes.ts

    export class Animal {
        move() { /* ... */ }
    }
    
    export class Plant {
        photosynthesize() { /* ... */ }
    }
    

    dog.ts

    import b = require('./baseTypes');
    
    export class Dog extends b.Animal {
        woof() { }
    }   
    

    tree.ts

    import b = require('./baseTypes');
    
    class Tree extends b.Plant {
    }
    

    LivingThings.ts

    import dog = require('./dog')
    import tree = require('./tree')
    
    export = {
        dog: dog,
        tree: tree
    }
    

    main.ts

    import LivingThings = require('./LivingThings');
    console.log(LivingThings.Tree)
    console.log(LivingThings.Dog)
    

    The idea is that your module themselves shouldn't care / know they are participating in a namespace, but this exposes your API to the consumer in a compact, sensible way which is agnostic to which type of module system you are using for the project.

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