feat(html/minifier): Remove duplicate attributes (#4474)

This commit is contained in:
Alexander Akait 2022-04-29 08:28:55 +03:00 committed by GitHub
parent f891c83f85
commit 750d6551fc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 30 additions and 18 deletions

View File

@ -1,5 +1,7 @@
#![deny(clippy::all)]
use swc_atoms::JsWord;
use swc_common::collections::AHashSet;
use swc_html_ast::*;
use swc_html_visit::{VisitMut, VisitMutWith};
@ -280,28 +282,32 @@ impl VisitMut for Minifier {
n.visit_mut_children_with(self);
n.children.retain(|child| !matches!(child, Child::Comment(comment) if !self.is_conditional_comment(&comment.data)));
let mut already_seen: AHashSet<JsWord> = Default::default();
n.attributes.retain(|attribute| {
if already_seen.contains(&attribute.name) {
return false;
}
already_seen.insert(attribute.name.clone());
if attribute.value.is_none() {
return true;
}
match &*attribute.name {
_ if self.is_default_attribute_value(
n.namespace,
&n.tag_name,
&attribute.name,
attribute.value.as_ref().unwrap(),
) =>
{
false
}
_ if matches!(&*attribute.name, "id" | "class" | "style")
&& (&*attribute.value.as_ref().unwrap()).trim().is_empty() =>
{
false
}
_ => true,
if self.is_default_attribute_value(
n.namespace,
&n.tag_name,
&attribute.name,
attribute.value.as_ref().unwrap(),
) || (matches!(&*attribute.name, "id" | "class" | "style")
&& (&*attribute.value.as_ref().unwrap()).trim().is_empty())
{
return false;
}
true
});
}

View File

@ -14,5 +14,8 @@
></div>
<img src="test.png" alt="one" alt="two">
<img src="test.png" alt="one" alt="two" alt="three">
<img src="test.png" alt="one" alt="two" alt="three" src="test2.png">
</body>
</html>

View File

@ -5,8 +5,11 @@
<title>Document</title>
</head>
<body>
<div data-test=one data-test=two></div>
<div data-test=one></div>
<img src=test.png alt=one>
<img src=test.png alt=one>
<img src=test.png alt=one>
<img src=test.png alt=one alt=two>
</body></html>