Destructuring or Something Different?

前端 未结 2 473
面向向阳花
面向向阳花 2021-01-27 14:24

This looks like destructuring:

const {getElementById, seedElements} = require(\'./utils\')

but I\'m confused about it. I\'m used to seeing something

相关标签:
2条回答
  • 2021-01-27 14:50

    You can think

    const {getElementById, seedElements} = require('./utils')
    

    as destructuring since when you export, you would write your export like

    module.exports = { getElementById, seedElements };
    

    or

    export { getElementById, seedElements };
    

    and while importing using require you would basically be importing the entire module and you can destructure the individual modules from it.

    const {getElementById, seedElements} = require('./utils')
    

    would be similar to

    const Utils = require('./utils');
    const { getElementById, seedElements } = Utils;
    

    with the import syntax, you would however import the named exports like

    import { getElementById, seedElements } from './utils';
    
    0 讨论(0)
  • 2021-01-27 14:54

    Yes, that is object destructuring.

    The require() function in Node.js can be used to import modules, JSON, and local files. For instance (from the docs):

    // Importing a local module:
    const myLocalModule = require('./path/myLocalModule');
    

    Calling require(moduleId) returns the object module.exports of moduleId ( module.exports contains precisely all properties that are made available by the module).

    0 讨论(0)
提交回复
热议问题