diff --git a/packages/babel-plugin-transform-property-literals/src/index.js b/packages/babel-plugin-transform-property-literals/src/index.js index 1dc6469e0..acdb949e2 100644 --- a/packages/babel-plugin-transform-property-literals/src/index.js +++ b/packages/babel-plugin-transform-property-literals/src/index.js @@ -1,5 +1,12 @@ "use strict"; +const safeIdentifierRegExp = /[^a-z0-9$_]/i; + +function isSafeKeyIdentifier(value) { + return !safeIdentifierRegExp.test(value) +} + + module.exports = function({ types: t }) { return { name: "transform-property-literals", @@ -8,6 +15,16 @@ module.exports = function({ types: t }) { ObjectProperty: { exit({ node }) { const key = node.key; + + // Handle the case where the incoming property key may not be a safe + // identifier that works in all browsers + if (t.isIdentifier(key)) { + if (!isSafeKeyIdentifier(key.name)) { + node.key = t.stringLiteral(key.name); + } + return; + } + if (!t.isStringLiteral(key)) { return; } @@ -15,7 +32,7 @@ module.exports = function({ types: t }) { if (key.value.match(/^\d+$/)) { node.key = t.numericLiteral(parseInt(node.key.value, 10)); node.computed = false; - } else if (t.isValidIdentifier(key.value)) { + } else if (isSafeKeyIdentifier(key.value)) { node.key = t.identifier(key.value); node.computed = false; }