Skip to content

Commit cbdb47f

Browse files
committedNov 13, 2021
fix: support CSS variables
Fixes #582
1 parent 985444d commit cbdb47f

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed
 

‎packages/hast-util-to-babel-ast/src/index.test.ts

+12
Original file line numberDiff line numberDiff line change
@@ -83,4 +83,16 @@ describe('hast-util-to-babel-ast', () => {
8383
`"<svg><text><tspan>{\\"<\\"}</tspan></text></svg>;"`,
8484
)
8585
})
86+
87+
it('properly converts style with variables', () => {
88+
const code = `<svg><path style="--index: 1; font-size: 24px;"></path><path style="--index: 2"></path></svg>`
89+
expect(transform(code)).toMatchInlineSnapshot(`
90+
"<svg><path style={{
91+
\\"--index\\": 1,
92+
fontSize: 24
93+
}} /><path style={{
94+
\\"--index\\": 2
95+
}} /></svg>;"
96+
`)
97+
})
8698
})

‎packages/hast-util-to-babel-ast/src/stringToObjectStyle.ts

+9-2
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,28 @@
22
import * as t from '@babel/types'
33
import { hyphenToCamelCase, isNumeric, trimEnd } from './util'
44

5+
const PX_REGEX = /^\d+px$/
6+
const MS_REGEX = /^-ms-/
7+
const VAR_REGEX = /^--/
8+
59
/**
610
* Determines if the CSS value can be converted from a
711
* 'px' suffixed string to a numeric value.
812
*/
913
const isConvertiblePixelValue = (value: string) => {
10-
return /^\d+px$/.test(value)
14+
return PX_REGEX.test(value)
1115
}
1216

1317
/**
1418
* Format style key into JSX style object key.
1519
*/
1620
const formatKey = (key: string) => {
21+
if (VAR_REGEX.test(key)) {
22+
return t.stringLiteral(key)
23+
}
1724
key = key.toLowerCase()
1825
// Don't capitalize -ms- prefix
19-
if (/^-ms-/.test(key)) key = key.substr(1)
26+
if (MS_REGEX.test(key)) key = key.substr(1)
2027
return t.identifier(hyphenToCamelCase(key))
2128
}
2229

0 commit comments

Comments
 (0)
Please sign in to comment.