【问题标题】:Can you call functions from an imported module without calling the module in node.js?您可以从导入的模块中调用函数而不调用 node.js 中的模块吗?
【发布时间】:2020-05-15 04:14:32
【问题描述】:

有点愚蠢的问题,只是想试试是否可以避免所需模块的名称。

例如:

const MATH = require('./maths.js');
HTTP.createServer(function (request, response) {
    response.write("Add 1 and 5: " + MATH.add(1, 5));
}).listen(8080);

// Add in the maths module
// function add(a, b) {
//     return a + b;
// }

我可以做一些以下事情吗?

response.write("加1和5:" + add(1,5));

【问题讨论】:

    标签: javascript node.js function module node-modules


    【解决方案1】:

    是的,您可以使用 ES6 解构。如何?像这样:

    const { add } = require('./maths.js');
    
    HTTP.createServer(function (request, response) {
        response.write("Add 1 and 5: " + add(1, 5));
    }).listen(8080);
    
    // Add in the maths module
    // function add(a, b) {
    //     return a + b;
    // }
    

    应该在 Node 10+ 中工作(甚至更早)

    【讨论】:

    • 这很完美!当导出模块是一个对象时,有没有办法让它工作?
    • 解构是一种通用语言特性。所以它可以是任何被导出的东西。
    猜你喜欢
    • 2019-08-03
    • 2018-01-28
    • 2021-09-22
    • 2015-11-12
    • 2013-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多