4

Guided by eslint's prefer-destructuring rule, I defined some constants like this:

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

Is it possible to export these constants by prefixing the statement by export?

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

This would seem natural, but eslint-plugin-import complains about a violation of the import/named rule: API_URL not found in '../constants'. In fact, this usage of export is also not described on the relevant MDN page.

Do we then have to repeat all constants in a separate export statement?

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

export {
    NODE_ENV,
    API_URL,
};
Claudio
  • 3,089
  • 2
  • 18
  • 22
  • 1
    @CertainPerformance No, that question has nothing to do with it. OP wants syntax for named exports, not build another object. – Bergi Jan 01 '19 at 13:53

2 Answers2

5

Is it possible to export these constants by prefixing the statement by export?

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

Yes, this is totally valid according to the spec. You can use destructuring patterns in the declarations of exported consts.

This would seem natural, but eslint-plugin-import complains about a violation of the import/named rule: API_URL not found in '../constants'.

Sounds like that plugin is broken. In fact, your exact use case was reported as working before.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • You're entirely right, this problem is triggered by a bug in eslint-plugin-import, reported in issue [#718](https://github.com/benmosher/eslint-plugin-import/issues/718), and fixed in PR [#1232](https://github.com/benmosher/eslint-plugin-import/pull/1232). The bug occurs only when the export uses destructuring with default values. I had edited the default values out of my question because I thought they were not relevant. – Claudio Jan 01 '19 at 20:53
  • @Claudio So does it work now after an update to the latest version, or did they break again what they fixed in #1232? – Bergi Jan 01 '19 at 20:56
  • I believe #1232 is not released yet. – Claudio Jan 01 '19 at 20:57
2

Article 15.2.2.3 of the spec says:

 ...
ExportDeclaration : export VariableStatement
ExportDeclaration : export Declaration

Article 13.1.4 says:

Declaration : LexicalDeclaration

Article 13.3 says:

LexicalDeclaration:
   LetOrConst BindingList;

LetOrConst :
 let
 const

BindingList :
 LexicalBinding
 BindingList, LexicalBinding

 LexicalBinding:
  BindingPattern Initializer

Therefore this:

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

is totally valid JavaScript.

Community
  • 1
  • 1
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151