我正在用 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。
到目前为止我已经尝试过
导出
Thing
类;这让我可以执行 1.3,但不能执行 1.2。导出
单例,使用export default new Thing()
;这让我可以执行 1.3,但不能执行 1.2。写这样的东西 -
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”文件中结合默认导出
和导出
:
export class Thing {
init() { }
}
export default new Thing();
关于javascript - 如何在 TypeScript 中将类方法动态导出为独立函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43246331/