Is `export { foo as default }` valid ES2015?

混江龙づ霸主 提交于 2020-01-02 02:24:52

问题


I received an issue on GitHub about my ES2015 module import/export validating plugin for ESLint not recognizing the default export in the following syntax:

export { 
    foo as default,
    bar
}

where my plugin will lint the following (equivalent?) syntax no problem:

export default foo;
export const bar = ..;

Both Babel and Esprima parse similar syntax without errors, and this works for code using Babel on both ends (import and export).

However, I'm not convinced the spec allows the former export { x as default } form:

For each IdentifierName n in ReferencedBindings of ExportClause : It is a Syntax Error if StringValue of n is a ReservedWord or if the StringValue of n is one of: "implements", "interface", "let", "package", "private", "protected", "public", "static", or "yield".

ReservedWord does include default, though I think one could argue that ReferencedBindings is referring specifically to the module-local identifier names that are being exported (i.e. foo) and not the exported name itself.

It also generally seems like a weird thing to be able to export reserved words; Babel will happily also allow something like

// ./foo.js
export { foo as yield }
// ./mod.js
import { yield as nonReservedIdentifier } from './foo'

So, in summary: is export { foo as default } a valid way to export a default in ES2015?


回答1:


Yes, ReferencedBindings refers only to the first IdentifierName. So

export { default as something } // or
export { default }

is invalid, but

export { something as default }

is not. ESLint will need a fix here.




回答2:


Yes, it's valid. I'll break it down.

  1. :

    export { foo as default }
    

    This matches the following productions (from least to most specific):

    export ExportClause
    ExportClause : { ExportsList }
    ExportsList : ExportSpecifier
    ExportSpecifier : IdentifierName as IdentifierName    
    
  2. Then you have the early error semantics:

    15.2.3.1 Static Semantics: Early Errors

    ExportDeclaration : export ExportClause ;

    For each IdentifierName n in ReferencedBindings of ExportClause : It is a Syntax Error if StringValue of n is a ReservedWord...

    These apply to any productions matching export ExportClause, including your example syntax. This invokes the ReferencedBindings algorithm.

  3. The ReferencedBindings algorithm that applies to that most specific production matched by this syntax is:

    ExportSpecifier : IdentifierName as IdentifierName

    Return a List containing the first IdentifierName.

So you see that the restriction regarding ReservedWord and the other listed values is only applied to the foo part of the syntax in your example.



来源:https://stackoverflow.com/questions/33155785/is-export-foo-as-default-valid-es2015

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!