代码之家  ›  专栏  ›  技术社区  ›  Diana Vazquez Romo

导出模块节点。js[重复]

  •  0
  • Diana Vazquez Romo  · 技术社区  · 9 年前

    var helper_formatModule = require('/formatModule.js'); 
    

    在formatModule内部。js,我也有一个声明,

    var helper_handleSentences = require('/handleSentences.js'); 
    

    如果是我原来的模块,mainModule。js需要在Handlementes中定义的函数。js模块可以访问它们吗?一、 e如果它导入了formatModule,一个具有可处理实体的模块,它是否可以访问这些实体?或者我需要进口无把手物品。直接使用js模块?

    1 回复  |  直到 9 年前
        1
  •  1
  •   PeterMader    9 年前

    仅在某个地方需要模块a(例如,在模块B中)并不能使a的功能在其他模块中可以访问。通常情况下,在模块B中甚至无法访问它们。

    要从另一个模块访问函数(或任何值),该另一个模块必须 他们以下场景将不起作用:

    // module-a.js
    function firstFunction () {}
    function secondFunction () {}
    
    // module-b.js
    var helper_handleSentences = require('/handleSentences.js'); 
    // do something with 'helper_handleSentences'
    module.exports = function (a) {
      return helper_handleSentences(a);
    }
    

    module-a.js 不导出任何内容。因此,变量 a 保存默认导出值,该值为空对象。

    1 mainModule.js

    // handleSentences.js
    function doSomethingSecret () {
      // this function can only be accessed in 'handleSentences.js'
    }
    function handleSentences () {
      // this function can be accessed in any module that requires this module
      doSomethingSecret();
    }
    module.exports = handleSentences;
    
    // formatModule.js
    var helper_handleSentences = require('/handleSentences.js'); 
    // do something with 'helper_handleSentences'
    module.exports = function (a) {
      return helper_handleSentences(a);
    };
    
    // mainModule.js
    var helper_handleSentences = require('/handleSentences.js');
    var helper_formatModule = require('/formatModule.js'); 
    // do something with 'helper_handleSentences' and 'helper_formatModule'
    

    2、将两个模块的导出值合并到一个对象中

    //handleSentences.js
    //此函数只能在“handlementes.js”中访问
    //可以在需要此模块的任何模块中访问此功能
    doSomethingSecret();
    }
    
    // formatModule.js
    var helper_handleSentences = require('/handleSentences.js'); 
    // do something with 'helper_handleSentences'
    function formatModule (a) {
      return helper_handleSentences(a);
    };
    module.exports = {
      handleSentences: helper_handleSentences,
      format: formatModule
    };
    
    // mainModule.js
    var helper_formatModule = require('/formatModule.js');
    // use both functions as methods
    helper_formatModule.handleSentences();
    helper_formatModule.format('...');