feat(compiler-sfc): <style vars> CSS variable injection

This commit is contained in:
Evan You
2020-07-10 16:30:58 -04:00
parent 6647e34ce7
commit bd5c3b96be
8 changed files with 280 additions and 19 deletions

View File

@@ -1,6 +1,10 @@
import postcss, { Root } from 'postcss'
import selectorParser, { Node, Selector } from 'postcss-selector-parser'
const animationNameRE = /^(-\w+-)?animation-name$/
const animationRE = /^(-\w+-)?animation$/
const cssVarRE = /\bvar\(--(global:)?([^)]+)\)/g
export default postcss.plugin('vue-scoped', (options: any) => (root: Root) => {
const id: string = options
const keyframes = Object.create(null)
@@ -129,21 +133,22 @@ export default postcss.plugin('vue-scoped', (options: any) => (root: Root) => {
}).processSync(node.selector)
})
// If keyframes are found in this <style>, find and rewrite animation names
// in declarations.
// Caveat: this only works for keyframes and animation rules in the same
// <style> element.
if (Object.keys(keyframes).length) {
root.walkDecls(decl => {
const hasKeyframes = Object.keys(keyframes).length
root.walkDecls(decl => {
// If keyframes are found in this <style>, find and rewrite animation names
// in declarations.
// Caveat: this only works for keyframes and animation rules in the same
// <style> element.
if (hasKeyframes) {
// individual animation-name declaration
if (/^(-\w+-)?animation-name$/.test(decl.prop)) {
if (animationNameRE.test(decl.prop)) {
decl.value = decl.value
.split(',')
.map(v => keyframes[v.trim()] || v.trim())
.join(',')
}
// shorthand
if (/^(-\w+-)?animation$/.test(decl.prop)) {
if (animationRE.test(decl.prop)) {
decl.value = decl.value
.split(',')
.map(v => {
@@ -158,8 +163,15 @@ export default postcss.plugin('vue-scoped', (options: any) => (root: Root) => {
})
.join(',')
}
})
}
}
// rewrite CSS variables
if (cssVarRE.test(decl.value)) {
decl.value = decl.value.replace(cssVarRE, (_, $1, $2) => {
return $1 ? `var(--${$2})` : `var(--${id}-${$2})`
})
}
})
})
function isSpaceCombinator(node: Node) {