`<script setup>
let a = 100
let b = 200
+ let foo = 300
</script>\n` +
`<style>
+ p{
+ width: calc(v-bind(foo) - 3px);
+ height: calc(v-bind('foo') - 3px);
+ }
div {
color: v-bind((a + b) / 2 + 'px' );
}
</style>`
)
expect(content).toMatch(`_useCssVars(_ctx => ({
- "${mockId}-_a___b____2____px__": ((_unref(a) + _unref(b)) / 2 + 'px' ),
+ "${mockId}-foo": (_unref(foo)),
+ "${mockId}-_a___b____2____px_": ((_unref(a) + _unref(b)) / 2 + 'px'),
"${mockId}-__a___b______2___a_": (((_unref(a) + _unref(b))) / (2 * _unref(a)))
})`)
assertCode(content)
import hash from 'hash-sum'
export const CSS_VARS_HELPER = `useCssVars`
-export const cssVarRE =
- /\bv-bind\s*\(\s*(?:'([^']+)'|"([^"]+)"|([^'"][^;]*))\s*\)/g
+// match v-bind() with max 2-levels of nested parens.
+const cssVarRE = /v-bind\s*\(((?:[^)(]+|\((?:[^)(]+|\([^)(]*\))*\))*)\)/g
export function genCssVarsFromList(
vars: string[],
}
}
+function noramlizeExpression(exp: string) {
+ exp = exp.trim()
+ if (
+ (exp[0] === `'` && exp[exp.length - 1] === `'`) ||
+ (exp[0] === `"` && exp[exp.length - 1] === `"`)
+ ) {
+ return exp.slice(1, -1)
+ }
+ return exp
+}
+
export function parseCssVars(sfc: SFCDescriptor): string[] {
const vars: string[] = []
sfc.styles.forEach(style => {
// ignore v-bind() in comments /* ... */
const content = style.content.replace(/\/\*([\s\S]*?)\*\//g, '')
while ((match = cssVarRE.exec(content))) {
- const variable = match[1] || match[2] || match[3]
+ const variable = noramlizeExpression(match[1])
if (!vars.includes(variable)) {
vars.push(variable)
}
Declaration(decl) {
// rewrite CSS variables
if (cssVarRE.test(decl.value)) {
- decl.value = decl.value.replace(cssVarRE, (_, $1, $2, $3) => {
- return `var(--${genVarName(id, $1 || $2 || $3, isProd)})`
+ decl.value = decl.value.replace(cssVarRE, (_, $1) => {
+ return `var(--${genVarName(id, noramlizeExpression($1), isProd)})`
})
}
}