【问题标题】:module.exports = function() how to callmodule.exports = function() 怎么调用
【发布时间】:2018-03-28 17:45:06
【问题描述】:

快速提问。

如果这样放置函数,我知道如何导出/导入函数

module.exports = {
    get: get,
    set: set
};

但我不知道如何从另一个文件运行此功能,我需要导入/导出什么?

 module.exports = function() {  
 var this = {};
 var that = {}; .... 
 much more code
 ....

【问题讨论】:

    标签: javascript angularjs node.js


    【解决方案1】:

    假设你有两个文件 A.js 和 B.js

    A.js

    module.exports = function() {  
       var this = {};
       var that = {}; .... 
       much more code
       ....
    }
    

    现在,如果您想在 B.js 中使用它,那么 A.js 将使用默认导出,并且它正在导出一个函数,因此您可以像这样使用它。

    var a = require('./A.js');
    // now as A.js is exporing a function so you can call that function by invoking a() function 
    // as you have inported it into variable name a
    a(); // this will call that
    

    如果你的函数需要这样的参数 module.exports = function(x, y) {

    那么你需要的可以像这样传递

    a(1, 2);

    【讨论】:

    • 谢谢您的好心先生
    • 如果您对答案感到满意,请点赞并接受它,这将对寻求类似帮助的其他人有所帮助。
    【解决方案2】:

    我不知道,当您说“知道如何导入/导出函数”时,您的意思是什么,但您可以这样做来定义一个函数,然后再从另一个文件中重用它。

    test.js

    module.exports = () => {
       console.log('This is a sample function')
    }
    

    use.js

    const myfunc = require('./test');
    myfunc(); // Would print This is a sample function
    

    我假设test.jsuse.js 在同一个目录中。

    您还可以在一个文件中包含多个函数: test.js

    module.exports.fn1 = () => {
       console.log('This is sample function1')
    

    }

    module.exports.fn2 = () => {
       console.log('This is sample function2')
    }
    

    use.js

    const myfunc1 = require('./test').fn1;
    myfunc1(); 
    console.log(require('./test').fn2); // Directly if you want
    

    您还可以阅读:

    • import 语句,目前 NodeJs 不支持,但可以使用 babel。

    【讨论】:

    • 非常感谢 Suhail!
    【解决方案3】:

    你有两种方法可以导出一个模块的功能(归档js):

    1) “默认” -> 如果您只需要在同一个存档中导出一个功能或其他数据。在这种情况下,您可以使用所需的别名导入:

    export default myFunction() {...}
    (In the other archive)
    import alias you want(the same name or other) from `'./name_of_the_archive_to_import';
    

    2) “多个功能或对象” -> 如果您必须在同一个存档中导出多个功能或其他数据。在这种情况下,您必须调用(导入)那些已声明的同名变量:

    export variable1;
    export variable2;
    ...
    (In the other archive)
    import variable1 from './name_of_the_archive_to_import';
    import variable2 from './name_of_the_archive_to_import';
    ...
    

    【讨论】:

    • 另外,您可以在一行中导入多个“导出”: import { variable1, variable2, ... } from './archive_to_export.js';或从'./archive_to_export.js'导入*作为imp(你想要的名字);在第一种情况下,您必须按其原始名称调用函数,而在第二种情况下,像这样:imp.(原始函数的名称)。
    猜你喜欢
    • 2022-07-04
    • 2019-08-22
    • 2016-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-07
    • 2016-06-22
    • 2012-05-14
    相关资源
    最近更新 更多