TypeScript默认常量导出

时间:2016-09-23 10:44:15

标签: typescript typescript1.8 typescript-typings

我们有一个TypeScript库,我们要发布到私有NPM环境,我们希望在其他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;

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

此外,我们以与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.

1 个答案:

答案 0 :(得分:3)

此处的错误消息有误,所以我为您解决了一个问题:https://github.com/Microsoft/TypeScript/issues/11092

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

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

    const foo: Foo;

    export default foo;
}
相关问题