Skip to content

Commit

Permalink
Handle memberExpression as css property (#1538)
Browse files Browse the repository at this point in the history
* Handle memberExpression as css property

* Fix prettier

* Fix formatting of module-traversal.test.ts

* Add changeset

---------

Co-authored-by: Grant Wong <[email protected]>
  • Loading branch information
liamqma and dddlr authored Oct 24, 2023
1 parent f8d01fa commit 4a11c5f
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/violet-spiders-help.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@compiled/babel-plugin': patch
---

Bugfix: handle memberExpression as CSS object property
6 changes: 6 additions & 0 deletions packages/babel-plugin/src/__fixtures__/mixins/objects.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,9 @@ export const cssCallExpressionMixin = {
color: 'red',
}),
};

export const cssPropertyNames = {
level1: {
level2: 'color',
},
};
11 changes: 11 additions & 0 deletions packages/babel-plugin/src/__tests__/module-traversal.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -634,5 +634,16 @@ describe('module traversal', () => {

expect(actual).toIncludeMultiple(['{color:red}', '{display:flex}', '{flex-direction:row}']);
});

it('should resolve member expression if used as CSS property', () => {
const actual = transform(`
import '@compiled/react';
import { cssPropertyNames } from '../__fixtures__/mixins/objects';
<div css={{ [cssPropertyNames.level1.level2]: 'blue' }} />
`);

expect(actual).toInclude('{color:blue}');
});
});
});
10 changes: 7 additions & 3 deletions packages/babel-plugin/src/utils/object-property-to-string.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,11 +53,15 @@ const expressionToString: ExpressionToString = (expression, meta) => {
if (t.isStringLiteral(expression) || t.isNumericLiteral(expression)) {
return String(expression.value);
}
// handles {[key]: 'value'}
if (t.isIdentifier(expression)) {
// handles {[key]: 'value'} and {[key.key]: 'value'}]}
if (t.isIdentifier(expression) || t.isMemberExpression(expression)) {
const evaluatedExpression = evaluateExpression(expression, meta);
if (evaluatedExpression.value === expression) {
throw new Error(`Cannot statically evaluate the value of "${expression.name}".`);
throw new Error(
`Cannot statically evaluate the value of "${
t.isIdentifier(expression) ? expression.name : expression.type
}`
);
}

return expressionToString(evaluatedExpression.value, evaluatedExpression.meta);
Expand Down

0 comments on commit 4a11c5f

Please sign in to comment.