Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor!: align css runtime #7306

Merged
merged 11 commits into from
Jul 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ packages/rspack/src/config/schema.check.js

packages/**/etc/**/*
packages/rspack-test-tools/template/**/*
packages/rspack-test-tools/src/helper/legacy/**/*
packages/rspack-test-tools/tests/**/*
packages/rspack-test-preact-refresh/tests/**/*
packages/rspack-plugin-mini-css-extract/test/cases/**/*
Expand Down
2 changes: 2 additions & 0 deletions biome.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"packages/rspack-plugin-preact-refresh/tests/**/*",
"packages/rspack-test-tools/template/**/*",
"packages/rspack-test-tools/tests/**/*",
"packages/rspack-test-tools/src/helper/legacy/**/*",
"packages/rspack-plugin-mini-css-extract/test/cases/**/*",
"packages/playground/**/*",
// --- ignore runtime code in browser
Expand Down Expand Up @@ -95,6 +96,7 @@
"tests/**/*",
"crates/**/*",
"packages/rspack-test-tools/template",
"packages/rspack-test-tools/src/helper/legacy/**/*",
// --- ignore runtime code in browser
"packages/rspack/hot",
"packages/rspack-dev-server/client",
Expand Down
1 change: 1 addition & 0 deletions crates/node_binding/binding.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1315,6 +1315,7 @@ export interface RawOutputOptions {
crossOriginLoading: RawCrossOriginLoading
cssFilename: JsFilename
cssChunkFilename: JsFilename
cssHeadDataCompression: boolean
hotUpdateMainFilename: string
hotUpdateChunkFilename: string
hotUpdateGlobal: string
Expand Down
2 changes: 2 additions & 0 deletions crates/rspack_binding_options/src/options/raw_output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,7 @@ pub struct RawOutputOptions {
pub cross_origin_loading: RawCrossOriginLoading,
pub css_filename: JsFilename,
pub css_chunk_filename: JsFilename,
pub css_head_data_compression: bool,
pub hot_update_main_filename: String,
pub hot_update_chunk_filename: String,
pub hot_update_global: String,
Expand Down Expand Up @@ -232,6 +233,7 @@ impl TryFrom<RawOutputOptions> for OutputOptions {
cross_origin_loading: value.cross_origin_loading.into(),
css_filename: value.css_filename.into(),
css_chunk_filename: value.css_chunk_filename.into(),
css_head_data_compression: value.css_head_data_compression,
hot_update_main_filename: value.hot_update_main_filename.into(),
hot_update_chunk_filename: value.hot_update_chunk_filename.into(),
hot_update_global: value.hot_update_global,
Expand Down
6 changes: 4 additions & 2 deletions crates/rspack_core/src/concatenated_module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ use rayon::prelude::*;
use regex::Regex;
use rspack_ast::javascript::Ast;
use rspack_collections::{
Identifiable, IdentifierIndexMap, IdentifierIndexSet, IdentifierMap, IdentifierSet,
Identifiable, Identifier, IdentifierIndexMap, IdentifierIndexSet, IdentifierMap, IdentifierSet,
};
use rspack_error::{Diagnosable, Diagnostic, DiagnosticKind, Result, TraceableError};
use rspack_hash::{HashDigest, HashFunction, RspackHash};
Expand Down Expand Up @@ -1601,7 +1601,9 @@ impl ConcatenatedModule {
if matches!(runtime_condition, RuntimeCondition::Boolean(false)) {
continue;
}
let module = reference.connection.module_identifier();

let module: &Identifier = reference.connection.module_identifier();

match references_map.entry(*module) {
indexmap::map::Entry::Occupied(mut occ) => {
let entry: &ConnectionWithRuntimeCondition = occ.get();
Expand Down
1 change: 1 addition & 0 deletions crates/rspack_core/src/options/output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ pub struct OutputOptions {
pub cross_origin_loading: CrossOriginLoading,
pub css_filename: Filename,
pub css_chunk_filename: Filename,
pub css_head_data_compression: bool,
pub hot_update_main_filename: FilenameTemplate,
pub hot_update_chunk_filename: FilenameTemplate,
pub hot_update_global: String,
Expand Down
88 changes: 78 additions & 10 deletions crates/rspack_plugin_css/src/parser_and_generator/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use rspack_core::{
diagnostics::map_box_diagnostics_to_module_parse_diagnostics,
rspack_sources::{BoxSource, ConcatSource, RawSource, ReplaceSource, Source, SourceExt},
BuildMetaDefaultObject, BuildMetaExportsType, ChunkGraph, ConstDependency, CssExportsConvention,
Dependency, DependencyTemplate, ErrorSpan, GenerateContext, LocalIdentName, Module,
Dependency, DependencyId, DependencyTemplate, ErrorSpan, GenerateContext, LocalIdentName, Module,
ModuleDependency, ModuleGraph, ModuleIdentifier, ModuleType, ParseContext, ParseResult,
ParserAndGenerator, RuntimeSpec, SourceType, TemplateContext, UsageState,
};
Expand All @@ -17,7 +17,7 @@ use rspack_error::{
};
use rustc_hash::FxHashSet;

use crate::utils::{css_modules_exports_to_string, LocalIdentOptions};
use crate::utils::{css_modules_exports_to_string, escape_css, LocalIdentOptions};
use crate::utils::{export_locals_convention, unescape};
use crate::{
dependency::{
Expand All @@ -33,8 +33,7 @@ use crate::{
static REGEX_IS_MODULES: Lazy<Regex> =
Lazy::new(|| Regex::new(r"\.module(s)?\.[^.]+$").expect("Invalid regex"));

pub(crate) static CSS_MODULE_SOURCE_TYPE_LIST: &[SourceType; 2] =
&[SourceType::JavaScript, SourceType::Css];
pub(crate) static CSS_MODULE_SOURCE_TYPE_LIST: &[SourceType; 1] = &[SourceType::Css];

pub(crate) static CSS_MODULE_EXPORTS_ONLY_SOURCE_TYPE_LIST: &[SourceType; 1] =
&[SourceType::JavaScript];
Expand All @@ -43,6 +42,7 @@ pub(crate) static CSS_MODULE_EXPORTS_ONLY_SOURCE_TYPE_LIST: &[SourceType; 1] =
pub struct CssExport {
pub ident: String,
pub from: Option<String>,
pub id: Option<DependencyId>,
}

pub type CssExports = IndexMap<String, IndexSet<CssExport>>;
Expand Down Expand Up @@ -217,6 +217,7 @@ impl ParserAndGenerator for CssParserAndGenerator {
CssExport {
ident: local_ident.clone(),
from: None,
id: None,
},
);
}
Expand Down Expand Up @@ -251,6 +252,7 @@ impl ParserAndGenerator for CssParserAndGenerator {
CssExport {
ident: local_ident.clone(),
from: None,
id: None,
},
);
}
Expand All @@ -267,14 +269,15 @@ impl ParserAndGenerator for CssParserAndGenerator {
from,
range,
} => {
let mut dep_id = None;
if let Some(from) = from
&& from != "global"
{
let from = from.trim_matches(|c| c == '\'' || c == '"');
dependencies.push(Box::new(CssComposeDependency::new(
from.to_string(),
ErrorSpan::new(range.start, range.end),
)));
let dep =
CssComposeDependency::new(from.to_string(), ErrorSpan::new(range.start, range.end));
dep_id = Some(*dep.id());
dependencies.push(Box::new(dep));
}
let exports = self.exports.get_or_insert_default();
for name in names {
Expand All @@ -296,6 +299,7 @@ impl ParserAndGenerator for CssParserAndGenerator {
from: from
.filter(|f| *f != "global")
.map(|f| f.trim_matches(|c| c == '\'' || c == '"').to_string()),
id: dep_id,
});
}
}
Expand All @@ -315,6 +319,7 @@ impl ParserAndGenerator for CssParserAndGenerator {
CssExport {
ident: value.to_string(),
from: None,
id: None,
},
);
}
Expand Down Expand Up @@ -384,11 +389,70 @@ impl ParserAndGenerator for CssParserAndGenerator {
data: generate_context.data,
};

let identifier = module.identifier();
let module_id = compilation
.chunk_graph
.get_module_id(identifier)
.clone()
.unwrap_or_default();

if let Some(exports) = &self.exports {
let mg = compilation.get_module_graph();
let unused =
get_unused_local_ident(exports, module.identifier(), generate_context.runtime, &mg);
let unused = get_unused_local_ident(exports, identifier, generate_context.runtime, &mg);
context.data.insert(unused);

let used = get_used_exports(exports, identifier, generate_context.runtime, &mg);

static RE: Lazy<Regex> = Lazy::new(|| Regex::new(r#"\\"#).expect("should compile"));
let module_id = RE.replace_all(&module_id, "/");

let meta_data = used
.iter()
.map(|(n, v)| {
let escaped = escape_css(n, false);
v.iter()
.map(|v| {
let composed = &v.id;

if let Some(composed) = composed {
let mg = compilation.get_module_graph();
let module = mg
.get_module_by_dependency_id(composed)
.expect("should have from dependency");
let module_id = compilation
.chunk_graph
.get_module_id(module.identifier())
.as_deref()
.expect("should have module id");

format!(
"{}:{}@{}/",
escaped,
escape_css(module_id, false),
escape_css(&v.ident, false)
)
} else {
format!("{}:{}/", escaped, &v.ident)
}
})
.collect::<Vec<_>>()
.join("")
})
.collect::<Vec<_>>()
.join("");

context.data.insert(CssUsedExports(format!(
"{}{}{}",
meta_data,
if self.es_module { "&" } else { "" },
escape_css(&module_id, false)
)));
} else {
context.data.insert(CssUsedExports(format!(
"{}{}",
if self.es_module { "&" } else { "" },
escape_css(&module_id, false)
)));
}

module.get_dependencies().iter().for_each(|id| {
Expand All @@ -409,6 +473,7 @@ impl ParserAndGenerator for CssParserAndGenerator {
};

generate_context.concatenation_scope = context.concatenation_scope.take();

Ok(source.boxed())
}
SourceType::JavaScript => {
Expand Down Expand Up @@ -544,3 +609,6 @@ fn get_unused_local_ident(
.collect(),
}
}

#[derive(Debug, Clone)]
pub struct CssUsedExports(pub String);
Loading
Loading