Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,43 @@ describe('@stylexjs/babel-plugin', () => {
`);
});

test('Test that sx attribute can be used instead of ...stylex.props', () => {
expect(
transform(
`
import stylex from 'stylex';
const styles = stylex.create({
red: {
color: 'red',
}
});
function Foo() {
return (
<>
<div id="test" sx={styles.red}>Hello World</div>
<div className="test" sx={styles.red} id="test">Hello World</div>
<div id="test" sx={styles.red} className="test">Hello World</div>
</>
);
}
`,
options,
),
).toMatchInlineSnapshot(`
"import _inject from "@stylexjs/stylex/lib/stylex-inject";
var _inject2 = _inject;
import stylex from 'stylex';
_inject2(".color-x1e2nbdu{color:red}", 3000);
function Foo() {
return <>
<div id="test" className="color-x1e2nbdu" data-style-src="npm-package:components/Foo.react.js:4">Hello World</div>
<div className="test" className="color-x1e2nbdu" data-style-src="npm-package:components/Foo.react.js:4" id="test">Hello World</div>
<div id="test" className="color-x1e2nbdu" data-style-src="npm-package:components/Foo.react.js:4" className="test">Hello World</div>
</>;
}"
`);
});

test('local dynamic styles', () => {
expect(
transform(
Expand Down
34 changes: 34 additions & 0 deletions packages/@stylexjs/babel-plugin/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,40 @@ function styleXTransform(): PluginObj<> {
},
},

JSXOpeningElement(path: NodePath<t.JSXOpeningElement>) {
const node = path.node;
if (
node.name.type !== 'JSXIdentifier' ||
typeof node.name.name !== 'string' ||
node.name.name[0] !== node.name.name[0].toLowerCase()
) {
return;
}
// console.log(path.node.attributes);
const relevantAttribute = path
.get('attributes')
.find(
(attr: NodePath<t.JSXAttribute | t.JSXSpreadAttribute>) =>
attr.isJSXAttribute() &&
attr.get('name').isJSXIdentifier() &&
attr.get('name').node.name === 'sx' &&
attr.get('value').isJSXExpressionContainer(),
);
if (relevantAttribute == null) {
console.log('no relevant attribute');
return;
}
const value = relevantAttribute.get('value').get('expression').node;
relevantAttribute.replaceWith(
t.jsxSpreadAttribute(
t.callExpression(
t.memberExpression(t.identifier('stylex'), t.identifier('props')),
[value],
),
),
);
},

CallExpression(path: NodePath<t.CallExpression>) {
if (path.parentPath.isVariableDeclarator()) {
const parentPath = path.parentPath;
Expand Down