New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Duplicate keys in object literals transpile to ES5-incompatible JS #2462
Comments
This will have to be done with another transform. Seems easy enough. |
Yeah, something like this seems to produce working code (horribly inefficiently though) if placed after the JSX transforms and before other export default function ({Plugin, types: t}) {
function getName (key) {
if ( t.isIdentifier(key) ) { return key.name; }
return key.value.toString();
}
return new Plugin('duplicate-property-keys-to-es5', {
visitor: {
ObjectExpression (node) {
const plainProps = node
.properties
.filter(prop => !t.isSpreadProperty(prop))
.filter(prop => !prop.computed);
plainProps
.filter((prop, index) =>
plainProps
.slice(0, index)
.some(previousProp =>
getName(prop.key) === getName(previousProp.key)
)
)
.forEach(prop => {
prop.computed = true;
prop.key = t.literal(getName(prop.key));
});
}
}
});
} |
Maybe this should be an
|
I think that sounds more like the job of a linter - there's plenty of other silly things you can do with the language that babel doesn't warn nor throw for. IMO what babel should do here is just produce valid JS. |
Yeah, I was thinking about that. I have always set my linters to throw on duplicated keys (and other duped ones like variable names) and I do agree that But then again the expected outcome is hard to say in a transpiling cases like with |
Perhaps this could be simple to implement if duplicate keys were treated the same way as computed keys. |
I see now that jussi-kalliokoski had already posted code to do my idea. [[ https://github.com/AgentME/babel-plugin-transform-es2015-duplicate-key-fix | I've just tweaked the code a little ]] and published it on NPM as "babel-plugin-transform-es2015-duplicate-key-fix", and then I published a fork of the es2015 preset that includes it as "babel-preset-es2015-dupkeyfix".
Just exclude the strict plugin which or use
Merged #3280 |
The following ES6 code:
generates the following code:
which will result in an error for ES5-compliant engines. I'm not sure what should be done here instead as duplicate keys are back to being valid in strict mode in ES6, but maybe something like this:
This bug also occurs with JSX:
becomes
The text was updated successfully, but these errors were encountered: