TypeScript 默认常量导出

TypeScript default constant export

我们有一个要发布到私有 NPM 环境的 TypeScript 库,我们想在其他 TS、ES6 或 ES5 项目中使用该库。

让库成为一个名为 foo 的 npm 包,它的主文件作为一个桶执行以下操作:

// Index.ts
import Foo from './Core/Foo';

export {default as Foo} from './Core/Foo';

const foo = new Foo();

export default foo;

我们想要导出主库 class 以及应用程序的默认实例,除非必要,否则无需创建新实例。

此外,我们在单独的存储库中创建了类型定义文件,其方式与 DefinitelyTyped 类似:

// foo.d.ts
declare namespace Foo {
  export class Foo {
    public constructor()
    // ...methods
  }

  const foo: Foo;

  export default foo;
}

declare module 'foo' {
  export = Foo;
}

运行 测试失败 error TS1063: An export assignment cannot be used in a namespace.

我的目标是像这样使用默认实例:

// ES5, browser env
window.Foo.foo.someMethod();

// ES6/TS
import foo from 'foo';

foo.someMethod();

如果有正确的方法,您有什么想法吗?

编辑

按照 @daniel-rosenwasser 的建议只声明模块之前是可行的,但是当我们尝试创建一个扩展第一个模块的新模块时出现问题。

例如:

// bar.d.ts
/// <reference path="../foo/foo.d.ts"/>

import {
  Foo
} from 'foo';

declare module 'bar' {
  export class Bar extends Foo {
    public constructor();
    // more methods
  }
}

及其测试:

// bar-tests.ts
/// <reference path="../foo/foo.d.ts"/>
/// <reference path="./bar.d.ts"/>

import foo, {
  Foo
} from 'foo';

import {
  Bar
} from 'bar';

namespace TestBar {
  {
    let result: Foo;
    result = foo;
  }

  {
    let result: Foo;
    result = new Bar();
  }
}

这次的错误是:

bar/bar-tests.ts: error TS2307: Cannot find module 'bar'.
bar/bar.d.ts: error TS2664: Invalid module name in augmentation, module 'bar' cannot be found.

这里的报错信息是错误的,所以我给大家开了个issue:https://github.com/Microsoft/TypeScript/issues/11092

如果你有一个 ES 风格的模块,你应该直接在环境模块声明中定义它:

declare module "foo" {
    export class Foo {
        public constructor()
        // ...methods
    }

    const foo: Foo;

    export default foo;
}