【问题标题】:How to export constants defined using object destructuring如何导出使用对象解构定义的常量
【发布时间】:2019-01-01 12:43:30
【问题描述】:

在 eslint 的 prefer-destructuring 规则的指导下,我定义了一些常量如下:

const {
    NODE_ENV,
    API_URL,
} = process.env;

是否可以通过在语句前加上export 来导出这些常量?

export const {
    NODE_ENV,
    API_URL,
} = process.env;

这看起来很自然,但eslint-plugin-import 抱怨违反了import/named 规则:API_URL not found in '../constants'。其实export的这种用法在相关的MDN page上也没有描述。

然后我们是否必须在单独的 export 语句中重复所有常量?

const {
    NODE_ENV,
    API_URL,
} = process.env;

export {
    NODE_ENV,
    API_URL,
};

【问题讨论】:

  • @CertainPerformance 不,这个问题与它无关。 OP 想要命名导出的语法,而不是构建另一个对象。

标签: javascript node.js ecmascript-6 eslint es6-modules


【解决方案1】:

是否可以通过在语句前加上前缀来导出这些常量 export?

export const {
    NODE_ENV,
    API_URL,
} = process.env;

是的,根据规范,这是完全有效的。您可以在导出的consts 的声明中使用解构模式。

这看起来很自然,但是 eslint-plugin-import 投诉违反 import/named 规则:API_URL not found in '../constants'.

听起来那个插件坏了。事实上,你之前的确切用例was reported as working

【讨论】:

  • 你说得对,这个问题是由 eslint-plugin-import 中的一个错误触发的,在 issue #718 中报告,并在 PR #1232 中修复。仅当导出使用具有默认值的解构时才会出现该错误。我已经编辑了我的问题中的默认值,因为我认为它们不相关。
  • @Claudio 那么它在更新到最新版本后现在可以工作了吗,还是他们再次破坏了他们在 #1232 中修复的内容?
  • 我相信#1232还没有发布。
【解决方案2】:

规范第 15.2.2.3 条规定:

 ...
ExportDeclaration : export VariableStatement
ExportDeclaration : export Declaration

第 13.1.4 条说:

Declaration : LexicalDeclaration

第 13.3 条说:

LexicalDeclaration:
   LetOrConst BindingList;

LetOrConst :
 let
 const

BindingList :
 LexicalBinding
 BindingList, LexicalBinding

 LexicalBinding:
  BindingPattern Initializer

因此:

 // ExportDeclaration
  export  // export
    // Declaration
    // LexicalDeclaration:
    const // LetOrConst
     // LexicalBindingList
     // LexicalBinding
     { NODE_ENV, API_URL } // BindingPattern
      = process.env; // Initializer

是完全有效的 JavaScript。

【讨论】:

  • 是的,这也是我发现的!
猜你喜欢
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-15
  • 2020-03-01
  • 2018-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多