Typescript 1.8 modules: import all files from folder

前端 未结 1 582
無奈伤痛
無奈伤痛 2020-12-03 20:43

I am building a big library with Typescript with like 100 separate ts files. Previously I used export module XXX (renamed to export namespace XXX

相关标签:
1条回答
  • 2020-12-03 21:16

    Both module resolution strategies that tsc provides don't support such a behavior. What your desired import statement

    import * as mylib from "./source/";
    

    is actually doing is to perform checks in this order:

    1. (does package.json have a typings key? If so, import this file)
    2. import * as mylib from "./source/index.ts";
    3. import * as mylib from "./source/index.tsx";
    4. import * as mylib from "./source/index.d.ts";
    

    I'm assuming you're using node-style module resolution here, which you probably are since it's the recommended way. Check the typescript docs for more details on how module resolution is done in typescript.

    Usually, what you're trying to accomplish is by creating an index.d.ts file, which serves as the entry point from which you're exporting the rest of your modules. I'm using angular2 as an example: Your common angular2 import looks like this:

    import { Injectable } from '@angular/core'
    

    core is just a directory that lives inside the @angular directory. Just like your source directory. However, in the core directory resides a index.d.ts file:

    /**
     * @module
     * @description
     * Starting point to import all public core APIs.
     */
    export * from './src/metadata';
    export * from './src/util';
    export * from './src/di';
    ....
    
    0 讨论(0)
提交回复
热议问题