How do I use namespaces with TypeScript external modules?

前端 未结 9 1319
陌清茗
陌清茗 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:24

    Several of the questions/comments I've seen around this subject sound to me as if the person is using Namespace where they mean 'module alias'. As Ryan Cavanaugh mentioned in one of his comments you can have a 'Wrapper' module re-export several modules.

    If you really want to import it all from the same module name/alias, combine a wrapper module with a paths mapping in your tsconfig.json.

    Example:

    ./path/to/CompanyName.Products/Foo.ts

    export class Foo {
        ...
    }
    


    ./path/to/CompanyName.Products/Bar.ts

    export class Bar {
        ...
    }
    


    ./path/to/CompanyName.Products/index.ts

    export { Foo } from './Foo';
    export { Bar } from './Bar';
    



    tsconfig.json

    {
        "compilerOptions": {
            ...
            paths: {
                ...
                "CompanyName.Products": ["./path/to/CompanyName.Products/index"],
                ...
            }
            ...
        }
        ...
    }
    



    main.ts

    import { Foo, Bar } from 'CompanyName.Products'
    

    Note: The module resolution in the output .js files will need to be handled somehow, such as with this https://github.com/tleunen/babel-plugin-module-resolver

    Example .babelrc to handle the alias resolution:

    {
        "plugins": [
            [ "module-resolver", {
                "cwd": "babelrc",
                "alias": {
                    "CompanyName.Products": "./path/to/typescript/build/output/CompanyName.Products/index.js"
                }
            }],
            ... other plugins ...
        ]
    }
    

提交回复
热议问题