代码之家  ›  专栏  ›  技术社区  ›  u84six

需要目录中的模块

  •  1
  • u84six  · 技术社区  · 7 年前

    对于CommonJS在节点环境中的工作方式,我有点困惑。我正在使用第三方库,它们的示例演示了如何访问以下特定模块:

    const {module1, module2} = require('somedir/someotherdir')
    

    我知道它将在目录中查找index.js,但它如何知道要加载哪些模块?在index.js文件中,我看到:

    module.exports = {
        someError,
        someOtherError,
        yetAnotherError,
    
        module1,
        module2,
        module3
    }
    

    上面要求的代码如何知道拉模块1和模块2,忽略模块3、SomeError、SomeOtherError、YetanOtherError

    1 回复  |  直到 7 年前
        1
  •  1
  •   Patrick Hund    7 年前

    这是一个叫做 破坏 与EcmaScript 2015,A.K.A.ES6一起推出。

    它基本上是一个快捷方式,可以让您将对象的属性直接放入变量中。

    在不破坏代码的情况下,编写代码的详细方法是:

    const someobject = require('somedir/someotherdir')
    const module1 = someobject.module1
    const module2 = someobject.module2
    

    所以 要求 语句只给您一个简单的旧javascript对象,然后您将得到 模块1 模2 的属性。

    此语法只是这样做的一个简短版本:

    const {module1, module2} = require('somedir/someotherdir')
    

    你也可以写,例如:

    const someobject = require('somedir/someotherdir')
    const {module1, module2} = someobject
    

    编写析构函数语句时,通过将名称放在大括号中来决定要在局部变量中保存对象的哪些属性。

    例如,如果你想 一些错误 其他错误 ,您可以这样写:

    const {someError, someOtherError} = require('somedir/someotherdir')
    

    为了得到一切:

    const {someError, someOtherError, yetAnotherError, module1, module2} = require('somedir/someotherdir')
    

    另请参见: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment