Skip to content

Commit e7b9216

Browse files
authored
Fix css module hashing with implicit CSS grid line names (parcel-bundler#129)
1 parent 3bdefdc commit e7b9216

File tree

4 files changed

+115
-71
lines changed

4 files changed

+115
-71
lines changed

src/bundler.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -736,11 +736,11 @@ mod tests {
736736
"#
737737
}, "/a.css");
738738
assert_eq!(res, indoc! { r#"
739-
.a_6lixEq_1 {
739+
._6lixEq_a {
740740
color: green;
741741
}
742742
743-
.a_6lixEq {
743+
._6lixEq_a {
744744
color: red;
745745
}
746746
"#});

src/css_modules.rs

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,10 +49,9 @@ pub(crate) struct CssModule<'a> {
4949

5050
impl<'a> CssModule<'a> {
5151
pub fn add_local(&mut self, exported: &str, local: &str) {
52-
let hash = &self.hash;
5352
self.exports.entry(exported.into())
5453
.or_insert_with(|| CssModuleExport {
55-
name: format!("{}_{}", local, hash),
54+
name: get_hashed_name(self.hash, local),
5655
composes: vec![],
5756
is_referenced: false
5857
});
@@ -65,7 +64,7 @@ impl<'a> CssModule<'a> {
6564
}
6665
std::collections::hash_map::Entry::Vacant(entry) => {
6766
entry.insert(CssModuleExport {
68-
name: format!("{}_{}", name, self.hash),
67+
name: get_hashed_name(self.hash, name),
6968
composes: vec![],
7069
is_referenced: true
7170
});
@@ -80,7 +79,7 @@ impl<'a> CssModule<'a> {
8079
parcel_selectors::parser::Component::Class(ref id) => {
8180
for name in &composes.names {
8281
let reference = match &composes.from {
83-
None => CssModuleReference::Local { name: format!("{}_{}", name.0, self.hash) },
82+
None => CssModuleReference::Local { name: get_hashed_name(self.hash, name.0.as_ref()) },
8483
Some(ComposesFrom::Global) => CssModuleReference::Global { name: name.0.as_ref().into() },
8584
Some(ComposesFrom::File(file)) => CssModuleReference::Dependency {
8685
name: name.0.to_string(),
@@ -107,10 +106,21 @@ impl<'a> CssModule<'a> {
107106
}
108107
}
109108

109+
fn get_hashed_name(hash: &str, name: &str) -> String {
110+
// Hash must come first so that CSS grid identifiers work.
111+
// This is because grid lines may have an implicit -start or -end appended.
112+
format!("{}_{}", hash, name)
113+
}
114+
110115
pub(crate) fn hash(s: &str) -> String {
111116
let mut hasher = DefaultHasher::new();
112117
s.hash(&mut hasher);
113118
let hash = hasher.finish() as u32;
114119

115-
ENCODER.encode(&hash.to_le_bytes())
120+
let hash = ENCODER.encode(&hash.to_le_bytes());
121+
if matches!(hash.as_bytes()[0], b'0'..=b'9') {
122+
format!("_{}", hash)
123+
} else {
124+
hash
125+
}
116126
}

0 commit comments

Comments
 (0)