【问题标题】:How can I make functions from one module directly available in others using Typescript / node.js?如何使用 Typescript / node.js 使一个模块中的功能直接在其他模块中可用?
【发布时间】:2014-09-05 20:54:30
【问题描述】:

我在 node.js 下运行这个 Javascript 代码。我在多个模块中声明函数并使用扩展实用程序,以便在其他模块中可用:

// File: util.js:
var Util = function () {
    this.doTask1 = function(name) { return 9; };
}
module.exports = new Util();

// File: base.js:
var util    = require('../../Utils/util.js');
var helpers = require('../../Utils/helpers.js');
var AdminBase = function () {
    var self = this;
    this.doTask2 = function(name) { return 99; };
}
module.exports = helpers.extend({}, util, new AdminBase());

// File: page.js:
var base = require('../Common/base.js');
var Page = function () {
   base.doTask1()
   base.doTask2()

// File: helpers.js
var extend = function (target) {
   var sources = [].slice.call(arguments, 1);
   sources.forEach(function (source) {
      for (var prop in source) {
         target[prop] = source[prop];
      }
   });
   return target;
};
module.exports.extend = extend;

我现在想用 Typescript 做同样的事情,我需要一些帮助。到目前为止,我知道我需要像这样编写模块的导入:

// File: util.ts
module Util {
   export function doTask1(name) { return 9; };
}
export = Util;

// File: base.ts
import util = require('../../Utils/util');
import helpers = require('../../Utils/helpers.js');
var AdminBase = function () {
   var self = this;
   this.doTask2 = function(name) { return 99; };
}
module.exports = helpers.extend({}, util, new AdminBase());

// File: page.js:
import base = require('../Common/base.js');
var Page = function () {
   base.doTask1()
   base.doTask2()

我对如何编写代码感到困惑,以便我可以访问 doTask1() 和 doTask2() 的功能与我使用第一种方法时的功能相同。

谁能给我建议,让我知道如何处理函数的导出,以便我可以像以前一样访问这些函数。

请注意,我不想要的是必须编码:

util.doTask1()
base.doTask2()

因为这开始变得令人困惑。

【问题讨论】:

    标签: javascript node.js typescript


    【解决方案1】:

    如果你想做

    base.doTask1()
    base.doTask2()
    

    你需要从base中导出doTask1/doTask2,即

    // File: base.ts
    import util = require('../../Utils/util');
    import helpers = require('../../Utils/helpers.js');
    
    export var doTask1 = util.doTask1;
    export var doTask2 = function(name) { return 99; };
    

    【讨论】:

      猜你喜欢
      • 2022-11-02
      • 1970-01-01
      • 2012-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-18
      • 2016-12-20
      • 1970-01-01
      相关资源
      最近更新 更多