Curly brackets (braces) in Node.js 'require' statement

后端 未结 2 1040
遇见更好的自我
遇见更好的自我 2020-11-27 03:11

I am trying to understand the difference between the two \'require\' statements below.

Specifically, what is the purpose of the { }s wrapped around

2条回答
  •  情深已故
    2020-11-27 03:12

    The second example uses destructuring.

    This will call the specific variable (including functions) that are exported from the required module.

    For example (functions.js):

    module.exports = {
       func1,
       func2
    }
    

    is included in your file:

    const { func1, func2 } = require('./functions')
    

    Now you can call them individually,

    func1()
    func2()
    

    as opposed to:

    const Functions = require('./functions')
    

    are called using dot notation:

    Functions.func1()
    Functions.func2()
    

    Hope this helps.

    You can read about destructuring here, it is a very useful part of ES6 and can be used with arrays as well as objects.

提交回复
热议问题