Skip to content

Commit

Permalink
Fix removal of quotes from property names
Browse files Browse the repository at this point in the history
  • Loading branch information
boopathi committed Jun 13, 2017
1 parent 7e2b315 commit 79c8772
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,13 @@ describe("transform-property-literals-plugin", () => {
"import": null
});
`);
expect(transform(source)).toBe(source);
const expected = unpad(`
({
default: null,
import: null
});
`);
expect(transform(source)).toBe(expected);
});

it("should not transform non-string properties", () => {
Expand All @@ -60,4 +66,30 @@ describe("transform-property-literals-plugin", () => {
`);
expect(transform(source)).toBe(source);
});

it("should not transform invalid es5 property names", () => {
const source = unpad(`
({
"\u2118": "wp",
"𐊧": "foo"
});
`);
expect(transform(source)).toBe(source);
});

it("should transform valid ES5 unicodes as property names", () => {
const source = unpad(`
({
"ಠ_ಠ": "bar",
"12e34": "wut"
})
`);
const expected = unpad(`
({
ಠ_ಠ: "bar",
12e34: "wut"
});
`);
expect(transform(source)).toBe(expected);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
"keywords": [
"babel-plugin"
],
"dependencies": {},
"dependencies": {
"esutils": "^2.0.2"
},
"devDependencies": {}
}
21 changes: 20 additions & 1 deletion packages/babel-plugin-transform-property-literals/src/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"use strict";

const esutils = require("esutils");

module.exports = function({ types: t }) {
return {
name: "transform-property-literals",
Expand All @@ -18,7 +20,7 @@ module.exports = function({ types: t }) {
node.key = t.numericLiteral(newProp);
node.computed = false;
}
} else if (t.isValidIdentifier(key.value)) {
} else if (isValidPropertyName(key.value)) {
node.key = t.identifier(key.value);
node.computed = false;
}
Expand All @@ -27,3 +29,20 @@ module.exports = function({ types: t }) {
}
};
};

// This currently targets es5 now.
// TODO:
// Target es6 after integration with babel-preset-env
function isValidPropertyName(name) {
if (typeof name !== "string") {
return false;
}

for (const char of name) {
if (!esutils.code.isIdentifierPartES5(char.charCodeAt(0))) {
return false;
}
}

return true;
}

0 comments on commit 79c8772

Please sign in to comment.