使用来自不同文件的类

时间:2016-10-24 11:22:51

标签: class typescript module export systemjs

关于如何在单独的文件中使用类拆分TypeScript模块有几个问题,但到目前为止还没有解决方案适用于我的问题。

我有一个模块(store),其中包含两个类(Person& SerialisedRecord)。当两个类都在一个文件中时,编译和导出工作正常。

现在我希望每个类(Person.ts& SerialisedRecord.ts)都有一个文件,遵循我已有的相同导出模式。但我不知道如何实现这一目标。

这是我最初的情况:

store.ts

export module store {

  export class Person {
    public fullName: string = '';

    constructor(firstName: string, lastName: string) {
      this.fullName = `${firstName} ${lastName}`;
    }
  }

  export class SerialisedRecord {   
    constructor(public serialised: string, public id: string) {}
  }

}

当我将store.ts编译为store.js(ES5)时,我得到了我想要的(SystemJS模块在一个模块中导出两个类):

System.register([], function(exports_1, context_1) {
    "use strict";
    var __moduleName = context_1 && context_1.id;
    var store;
    return {
        setters:[],
        execute: function() {
            (function (store) {
                var Person = (function () {
                    function Person(firstName, lastName) {
                        this.fullName = '';
                        this.fullName = firstName + " " + lastName;
                    }
                    return Person;
                }());
                store.Person = Person;
                var SerialisedRecord = (function () {
                    function SerialisedRecord(serialised, id) {
                        this.id = id;
                        this.serialised = serialised;
                    }
                    return SerialisedRecord;
                }());
                store.SerialisedRecord = SerialisedRecord;
            })(store = store || (store = {}));
            exports_1("store", store);
        }
    }
});

现在我试着这样做:

export module store {
  export {Person} from "./Person";
  export {SerialisedRecord} from "./SerialisedRecord";
}

但它没有告诉我:

  

错误TS1194:命名空间中不允许导出声明。

你能告诉我我做错了吗?

这是我的 tsconfig.json

{
  "compilerOptions": {
    "module": "system",
    "moduleResolution": "node",
    "noEmitOnError": true,
    "noImplicitAny": false,
    "noImplicitReturns": true,
    "removeComments": true,
    "target": "es5"
  },
  "exclude": [
    "node_modules",
    "typings/browser",
    "typings/browser.d.ts"
  ]
}

1 个答案:

答案 0 :(得分:3)

如果删除商店模块,它的效果很好:

store.ts:

export { Person } from "./Person";
export { SerialisedRecord } from "./SerialisedRecord";

index.ts:

import { Person, SerialisedRecord } from "./store";

let p = new Person("first", "last");

修改

如果必须保留命名空间结构,可以尝试类似:

import Person from "./Person";
import SerialisedRecord from "./SerialisedRecord";

export default {
    store: {
        Person,
        SerialisedRecord
    }
}