繁体   English   中英

如何在ClassScript中将Class方法动态导出为独立函数?

[英]How do I dynamically export Class methods as standalone functions in TypeScript?

我在TypeScript中重写一个旧的NPM模块,我遇到了一个有趣的问题。

该模块在当前状态下看起来像这样 -

1.1 my-module.js

export function init(options) {
    //initialize module
}

export function doStuff(params) {
    //do stuff with options and other things
}

1.2 example.js

var m = require('my-module');
m.init({thing: 'doodad'});
m.doStuff('bwoah');

我在TS中重写这个(针对ES6),并计划将模块编写为一个可以接受构造函数(代替init() )的类,让我写出像 -

1.3 example-new.js

import {Thing} from 'my-module';
const aThing1 = new Thing({thing: 'doodad'});
const aThing2 = new Thing();
aThing2.init({thing: 'doodad'});
aThing1.doStuff('bwoah');
aThing2.doStuff('bwoah');
// If I can do at least one of aThing1 or aThing2, I can die a happy man.

重写的TypeScript模块看起来像这样 -

1.4 my-module-new.js

class Thing {
    options: Object;
    constructor(options: Object) {
        this.options = options;
    }
    init(options: Object) {
        this.options = options;
        return this;
    }
    doStuff(thingForStuff: string) {
        // ...
    }
}

我想要实现的目标

我还希望保持与旧API的完全向后兼容性。 理想情况下,我应该能够做到1.2和1.3

到目前为止我尝试过的

  1. export Thing班; 这让我做1.3,但不是1.2。
  2. export单例, export default new Thing() ; 这让我做1.3,但不是1.2。
  3. 写这样的东西 -

     export class Thing { options: Object; constructor(options: Object) { this.options = options; } init(options: Object) { this.options = options; return this; } doStuff(thingForStuff: string) { // ... } } const singleThing = new Thing(); export function init(options) { return singleThing.init(options); } export function doStuff(string) { return singleThing.doStuff(string); } 

这适用于1.2和1.3 - 但基本上复制每个函数似乎很乏味。

当然必须有更优雅的方式来做到这一点?

我们可以! ©在“Thing”文件中组合default exportexport

export class Thing {
    init() { }
}

export default new Thing();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM