node.js - typescript : Add a method on a class from another module/Populate a namespace from different modules

标签 node.js module typescript commonjs partial-classes

故事

我正在构建一个用于数学运算的模块化库。我还想将库分为多个模块:核心关系向量等。这些模块可以单独使用(但都依赖于 core 模块)

  1. 我知道不可能使用部分类 How do I split a TypeScript class into multiple files?/https://github.com/Microsoft/TypeScript/issues/563

问题:

core 模块定义了 Set 类,它是一个数学集合。它定义了Set#addSet#remove等操作。

不过,可选关系模块在Set类上添加了一个Set#product运算符。

其他模块也可以在 Set 类上添加其他操作。我希望保留在我认为合适时添加功能的可能性。

问题

  1. 使用 typescript,如何在驻留在另一个模块中的类上添加方法?

  2. 如何安排输入,以便我的库的用户仅在安装了关系模块时才能在其代码补全中看到Set#product?否则他只能看到 #add#remove 操作?

我正在为 node.js 开发这个库,但也使用 browserify 将其捆绑以供浏览器使用。

// core/set.ts 

export class Set {
  add(element){}
  remove(element){}
}


// relational/set.ts

import {Set} from './../core/set.ts';

Set.prototype.product = function(){} // ?


// app/index.js

import {core} from 'mylib';

var set = new Set();
set.add();
set.remove();
// set.product() is not available


// app/index2.js

import {core} from 'mylib';
import {relational} from 'mylib';

var set = new Set();
set.add();
set.remove();
set.product() //is available

奖励问题

所有这些模块都可以通过公共(public)命名空间使用,我们将其称为MyLibrarycore 模块添加了 MyLibrary.Corerelational 模块将一些对象添加到 MyLibrary.Core 中,并且还添加了 MyLibrary.Relational

假设我发布了另一个模块,仅用作其他模块的外观。我们将此模块称为 my-library

如果用户使用 npm 安装 my-librarycorerelational 模块。

npm install my-library && npm install core and nom-install relational

在客户端应用程序中,我希望库的用户只需编写

var lib = require('my-library');

然后,my-library 会自动检查所有已安装的 MyLibrary 模块,需要它们并填充 MyLibrary 命名空间并返回它。

我如何在 Node 和浏览器环境中第一次访问my-library模块时告诉它

  1. 检查是否有任何可用的 MyLibrary 模块(浏览器和 Node 环境)
  2. 为每个模块运行一个方法(将它们安装在命名空间中)
  3. 返回那个漂亮的水果命名空间

最佳答案

如果您只是编写声明文件,则可以使用接口(interface)代替并执行类似 moment-timezone 的操作确实如此。

时刻.d.ts

declare module moment {
    interface Moment {
        // ...
    }

    interface MomentStatic {
        // ...
    }
}
declare module 'moment' {
    var _tmp: moment.MomentStatic;
    export = _tmp;
}

时刻时区.d.ts

只需重新声明具有额外功能的相同接口(interface)即可。

declare module moment {
    interface Moment {
        tz(): void;
    }

    interface MomentStatic {
        tz(): void;
    }
}
declare module 'moment-timezone' {
    var _tmp: moment.MomentStatic;
    export = _tmp;
}

两个包现在是相同的,并且 moment 自动获取新方法。

关于node.js - typescript : Add a method on a class from another module/Populate a namespace from different modules,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34448251/

相关文章:

node.js - process.cwd() 与 __dirname 有什么区别?

node.js - Mongoose :Find and filter nested array

powershell - 如何使用模块 list 导出 PowerShell 模块别名?

java - 如何判断包属于哪个模块?

arrays - typescript - 初始化二维数组错误

javascript - 如何模拟使用在 Node 模块中导出的导入(ES6 typescript)进行单元测试的外部注入(inject)库

javascript - 使用 mocha 对 Node 模块进行单元测试,模块变量行为异常

android - 在 android studio gradle 文件中全局设置 lintOptions

javascript - 类属性 : "Object is possibly undefined" in TypeScript

javascript - 我们如何在将 javascript 代码发送给 nodejs 中的用户之前执行它?