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 May 22, 2017
1 parent b79fb8a commit 8474582
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 19 deletions.
Expand Up @@ -24,48 +24,72 @@ describe("transform-property-literals-plugin", () => {
});

it("should not strip necessaary quotes for numeric like things", () => {
const source = unpad(
`
const source = unpad(`
var data = {
"00": 1,
"01": 2
};
`
);
`);
expect(transform(source)).toBe(source);
});

it("should not transform invalid identifiers", () => {
const source = unpad(
`
const source = unpad(`
({
"default": null,
"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", () => {
const source = unpad(
`
const source = unpad(`
({
foo: null
});
`
);
`);
expect(transform(source)).toBe(source);
});

it("should not transform propety keys that are computed", () => {
const source = unpad(
`
const source = unpad(`
({
[a]: null
});
`
);
`);
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);
});
});
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
@@ -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 8474582

Please sign in to comment.