问题
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
inReferencedBindings
ofExportClause
: 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.
:
export { foo as default }
This matches the following productions (from least to most specific):
export ExportClause ExportClause : { ExportsList } ExportsList : ExportSpecifier ExportSpecifier : IdentifierName as IdentifierName
Then you have the early error semantics:
15.2.3.1 Static Semantics: Early Errors
ExportDeclaration : export ExportClause ;
For each
IdentifierName
n
inReferencedBindings
ofExportClause
: It is a Syntax Error ifStringValue
ofn
is aReservedWord
...These apply to any productions matching
export ExportClause
, including your example syntax. This invokes theReferencedBindings
algorithm.The ReferencedBindings algorithm that applies to that most specific production matched by this syntax is:
ExportSpecifier : IdentifierName as IdentifierName
Return a
List
containing the firstIdentifierName
.
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