feat(minifier): implement converting template literals to strings (#6486)

basically:
```
`hello ${"world"}`
```
 now becomes:
```
"hello world"
```
This commit is contained in:
camc314 2024-10-13 06:26:32 +00:00
parent 14d0590b0b
commit e5a6f5de6a
2 changed files with 20 additions and 9 deletions

View file

@ -112,6 +112,13 @@ impl<'a> Traverse<'a> for PeepholeSubstituteAlternateSyntax {
self.try_fold_chain_call_expression(call_expr, ctx);
}
}
Expression::TemplateLiteral(_) => {
if let Some(val) = ctx.get_string_value(expr) {
let new_expr = ctx.ast.string_literal(expr.span(), val);
*expr = ctx.ast.expression_from_string_literal(new_expr);
self.changed = true;
}
}
_ => {}
}
}
@ -782,7 +789,6 @@ mod test {
}
#[test]
#[ignore]
fn test_template_string_to_string() {
test("`abcde`", "'abcde'");
test("`ab cd ef`", "'ab cd ef'");

View file

@ -322,14 +322,19 @@ pub trait NodeUtil {
Some(Cow::Borrowed(string_literal.value.as_str()))
}
Expression::TemplateLiteral(template_literal) => {
// TODO: I don't know how to iterate children of TemplateLiteral in order,so only checkout string like `hi`.
// Closure-compiler do more: [case TEMPLATELIT](https://github.com/google/closure-compiler/blob/e13f5cd0a5d3d35f2db1e6c03fdf67ef02946009/src/com/google/javascript/jscomp/NodeUtil.java#L241-L256).
template_literal
.quasis
.first()
.filter(|quasi| quasi.tail)
.and_then(|quasi| quasi.value.cooked.as_ref())
.map(|cooked| Cow::Borrowed(cooked.as_str()))
let mut str = String::new();
for (i, quasi) in template_literal.quasis.iter().enumerate() {
str.push_str(quasi.value.cooked.as_ref()?);
if i < template_literal.expressions.len() {
let expr = &template_literal.expressions[i];
let value = self.get_string_value(expr)?;
str.push_str(&value);
}
}
Some(Cow::Owned(str))
}
Expression::Identifier(ident) => {
let name = ident.name.as_str();