Skip to content

Commit aa9348f

Browse files
committed
feat: 处理css变量,变成lpx
1 parent 52ba24b commit aa9348f

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

src/parse_style_properties.rs

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,10 +92,23 @@ pub fn parse_style_properties(properties: &Vec<(String, Property)>) -> DeclsAndV
9292
let id_ = custom.name.to_css_string(Default::default()).unwrap();
9393
// css 变量
9494
if id_.starts_with("--") {
95+
96+
let re = regex::Regex::new(r#"\b(\d+(?:px|vw|vh))\b"#).unwrap();
97+
let var_str = value.value_to_css_string(PrinterOptions::default()).unwrap().to_string();
98+
let result = re.replace_all(var_str.as_str(), |caps: &regex::Captures| {
99+
let value = &caps[1];
100+
let unit = &value[value.len() - 2..];
101+
let parsed_value: i32 = value[..value.len() - 2].parse().unwrap();
102+
if unit == "px" {
103+
format!("{}lpx", parsed_value)
104+
} else {
105+
format!("{}{}", parsed_value, unit)
106+
}
107+
});
95108
variable_properties.push(
96109
CssVariable {
97110
id: id_,
98-
value: value.value_to_css_string(PrinterOptions::default()).unwrap().to_string(),
111+
value: result.to_string(),
99112
}
100113
);
101114
}

src/style_propetries/macros.rs

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,21 @@ macro_rules! generate_prop_name {
1111
macro_rules! generate_expr_lit_str {
1212
($var:expr) => {{
1313
use swc_core::ecma::ast::*;
14-
Expr::Lit(Lit::Str($var.into()))
14+
15+
let re = regex::Regex::new(r#"\b(\d+(?:px|vw|vh))\b"#).unwrap();
16+
let var_str = $var.to_string();
17+
let result = re.replace_all(var_str.as_str(), |caps: &regex::Captures| {
18+
let value = &caps[1];
19+
let unit = &value[value.len() - 2..];
20+
let parsed_value: i32 = value[..value.len() - 2].parse().unwrap();
21+
if unit == "px" {
22+
format!("{}lpx", parsed_value)
23+
} else {
24+
format!("{}{}", parsed_value, unit)
25+
}
26+
});
27+
28+
Expr::Lit(Lit::Str(result.into()))
1529
}};
1630
}
1731

0 commit comments

Comments
 (0)