Skip to content

Commit

Permalink
feat: mini-css-extract-plugin
Browse files Browse the repository at this point in the history
  • Loading branch information
JSerFeng committed Feb 22, 2024
1 parent c885fb6 commit ea0d21b
Show file tree
Hide file tree
Showing 46 changed files with 2,678 additions and 76 deletions.
22 changes: 22 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 14 additions & 1 deletion crates/node_binding/binding.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,8 @@ export enum BuiltinPluginName {
HtmlRspackPlugin = 'HtmlRspackPlugin',
SwcJsMinimizerRspackPlugin = 'SwcJsMinimizerRspackPlugin',
SwcCssMinimizerRspackPlugin = 'SwcCssMinimizerRspackPlugin',
BundlerInfoRspackPlugin = 'BundlerInfoRspackPlugin'
BundlerInfoRspackPlugin = 'BundlerInfoRspackPlugin',
CssExtractPlugin = 'CssExtractPlugin'
}

export function cleanupGlobalTrace(): void
Expand Down Expand Up @@ -775,6 +776,17 @@ export interface RawCrossOriginLoading {
boolPayload?: boolean
}

export interface RawCssExtractPluginOption {
filename: string
chunkFilename: string
ignoreOrder: boolean
insert?: string
attributes: Record<string, string>
linkType?: string
runtime: boolean
pathinfo: boolean
}

export interface RawCssModulesConfig {
localsConvention: "asIs" | "camelCase" | "camelCaseOnly" | "dashes" | "dashesOnly"
localIdentName: string
Expand Down Expand Up @@ -1247,6 +1259,7 @@ export interface RawSplitChunksOptions {
automaticNameDelimiter?: string
maxAsyncRequests?: number
maxInitialRequests?: number
defaultSizeTypes: Array<string>
minChunks?: number
hidePathInfo?: boolean
minSize?: number
Expand Down
1 change: 1 addition & 0 deletions crates/rspack_binding_options/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ rspack_plugin_devtool = { path = "../rspack_plugin_devtool" }
rspack_plugin_ensure_chunk_conditions = { path = "../rspack_plugin_ensure_chunk_conditions" }
rspack_plugin_entry = { path = "../rspack_plugin_entry" }
rspack_plugin_externals = { path = "../rspack_plugin_externals" }
rspack_plugin_extract_css = { path = "../rspack_plugin_extract_css" }
rspack_plugin_hmr = { path = "../rspack_plugin_hmr" }
rspack_plugin_html = { path = "../rspack_plugin_html" }
rspack_plugin_javascript = { path = "../rspack_plugin_javascript" }
Expand Down
10 changes: 10 additions & 0 deletions crates/rspack_binding_options/src/options/raw_builtins/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
mod raw_banner;
mod raw_bundle_info;
mod raw_copy;
mod raw_css_extract;
mod raw_html;
mod raw_limit_chunk_count;
mod raw_mf;
Expand Down Expand Up @@ -67,6 +68,7 @@ pub use self::{
};
use self::{
raw_bundle_info::{RawBundlerInfoModeWrapper, RawBundlerInfoPluginOptions},
raw_css_extract::RawCssExtractPluginOption,
raw_mf::{RawConsumeSharedPluginOptions, RawContainerReferencePluginOptions, RawProvideOptions},
};
use crate::{
Expand Down Expand Up @@ -138,6 +140,7 @@ pub enum BuiltinPluginName {
SwcJsMinimizerRspackPlugin,
SwcCssMinimizerRspackPlugin,
BundlerInfoRspackPlugin,
CssExtractPlugin,
}

#[napi(object)]
Expand Down Expand Up @@ -391,6 +394,13 @@ impl BuiltinPlugin {
.boxed(),
)
}
BuiltinPluginName::CssExtractPlugin => {
let plugin = rspack_plugin_extract_css::plugin::PluginCssExtract::new(
downcast_into::<RawCssExtractPluginOption>(self.options)?.into(),
)
.boxed();
plugins.push(plugin);
}
}
Ok(())
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
use std::collections::HashMap;

use napi_derive::napi;
use rspack_core::Filename;
use rspack_plugin_extract_css::plugin::{CssExtractOptions, InsertType};

#[napi(object)]
pub struct RawCssExtractPluginOption {
pub filename: String,
pub chunk_filename: String,
pub ignore_order: bool,
pub insert: Option<String>,
pub attributes: HashMap<String, String>,
pub link_type: Option<String>,
pub runtime: bool,
pub pathinfo: bool,
}

impl From<RawCssExtractPluginOption> for CssExtractOptions {
fn from(value: RawCssExtractPluginOption) -> Self {
Self {
filename: Filename::from(value.filename),
chunk_filename: Filename::from(value.chunk_filename),
ignore_order: value.ignore_order,
insert: value
.insert
.map(|insert| {
if insert.starts_with("function") || insert.starts_with('(') {
InsertType::Fn(insert)
} else {
InsertType::Selector(insert)
}
})
.unwrap_or(InsertType::Default),
attributes: value.attributes.into_iter().collect(),
link_type: value.link_type,
runtime: value.runtime,
pathinfo: value.pathinfo,
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ pub struct RawSplitChunksOptions {
pub automatic_name_delimiter: Option<String>,
pub max_async_requests: Option<u32>,
pub max_initial_requests: Option<u32>,
// pub default_size_types: Option<Vec<SizeType>>,
pub default_size_types: Vec<String>,
pub min_chunks: Option<u32>,
pub hide_path_info: Option<bool>,
pub min_size: Option<f64>,
Expand Down Expand Up @@ -114,7 +114,11 @@ impl From<RawSplitChunksOptions> for rspack_plugin_split_chunks::PluginOptions {
normalize_raw_chunk_name(name)
});

let default_size_types = [SourceType::JavaScript, SourceType::Unknown];
let default_size_types = raw_opts
.default_size_types
.into_iter()
.map(|size_type| SourceType::from(size_type.as_str()))
.collect::<Vec<_>>();

let create_sizes = |size: Option<f64>| {
size
Expand Down
3 changes: 1 addition & 2 deletions crates/rspack_binding_values/src/chunk_graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,8 +64,7 @@ pub fn get_chunk_modules_iterable_by_source_type(
.chunk_graph
.get_chunk_modules_iterable_by_source_type(
&ChunkUkey::from(js_chunk_ukey as usize),
SourceType::try_from(source_type.as_str())
.map_err(|e| napi::Error::from_reason(e.to_string()))?,
SourceType::from(source_type.as_str()),
&compilation.module_graph,
)
.filter_map(|module| module.to_js_module().ok())
Expand Down
24 changes: 10 additions & 14 deletions crates/rspack_core/src/compiler/execute_module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ impl Compilation {
let m = self
.module_graph
.module_by_identifier(&m)
.expect("should have module");
.unwrap_or_else(|| panic!("should have module: {m}"));
for m in self.module_graph.get_outgoing_connections(m) {
// TODO: handle circle
if !modules.contains(&m.module_identifier) {
Expand Down Expand Up @@ -369,19 +369,15 @@ impl Compilation {
.module_by_identifier(&module)
.expect("todo");

tx_clone
.send((
module,
Some(
compilation
.module_graph
.get_outgoing_connections(m)
.into_iter()
.map(|conn| conn.module_identifier)
.collect(),
),
))
.expect("todo");
let deps = compilation
.module_graph
.get_outgoing_connections(m)
.into_iter()
.map(|conn| conn.module_identifier)
.filter(|m| compilation.module_graph.module_by_identifier(m).is_none())
.collect();

tx_clone.send((module, Some(deps))).expect("todo");
}),
);
}
Expand Down
32 changes: 14 additions & 18 deletions crates/rspack_core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ pub enum SourceType {
Remote,
ShareInit,
ConsumeShared,
Custom(Ustr),
#[default]
Unknown,
}
Expand All @@ -130,29 +131,24 @@ impl std::fmt::Display for SourceType {
SourceType::ShareInit => write!(f, "share-init"),
SourceType::ConsumeShared => write!(f, "consume-shared"),
SourceType::Unknown => write!(f, "unknown"),
SourceType::Custom(source_type) => f.write_str(source_type),
}
}
}

impl TryFrom<&str> for SourceType {
type Error = rspack_error::Error;

fn try_from(value: &str) -> Result<Self, Self::Error> {
impl From<&str> for SourceType {
fn from(value: &str) -> Self {
match value {
"javascript" => Ok(Self::JavaScript),
"css" => Ok(Self::Css),
"wasm" => Ok(Self::Wasm),
"asset" => Ok(Self::Asset),
"expose" => Ok(Self::Expose),
"remote" => Ok(Self::Remote),
"share-init" => Ok(Self::ShareInit),
"consume-shared" => Ok(Self::ConsumeShared),
"unknown" => Ok(Self::Unknown),

_ => {
use rspack_error::error;
Err(error!("invalid source type: {value}"))
}
"javascript" => Self::JavaScript,
"css" => Self::Css,
"wasm" => Self::Wasm,
"asset" => Self::Asset,
"expose" => Self::Expose,
"remote" => Self::Remote,
"share-init" => Self::ShareInit,
"consume-shared" => Self::ConsumeShared,
"unknown" => Self::Unknown,
other => SourceType::Custom(other.into()),
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions crates/rspack_core/src/plugin/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use rspack_error::{IntoTWithDiagnosticArray, Result, TWithDiagnosticArray};
use rspack_hash::RspackHashDigest;
use rspack_loader_runner::{Content, LoaderContext, ResourceData};
use rspack_sources::{BoxSource, Source};
use rustc_hash::FxHashMap;
use rspack_util::fx_dashmap::FxDashMap;
use tokio::sync::mpsc::UnboundedSender;

use crate::{
Expand Down Expand Up @@ -615,7 +615,7 @@ pub type BoxedParserAndGeneratorBuilder =

pub struct ApplyContext<'c> {
pub(crate) registered_parser_and_generator_builder:
&'c mut FxHashMap<ModuleType, BoxedParserAndGeneratorBuilder>,
&'c mut FxDashMap<ModuleType, BoxedParserAndGeneratorBuilder>,
pub compiler_hooks: &'c mut CompilerHooks,
}

Expand Down
6 changes: 4 additions & 2 deletions crates/rspack_core/src/plugin/plugin_driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use std::{
use rspack_error::{Diagnostic, Result, TWithDiagnosticArray};
use rspack_loader_runner::{LoaderContext, ResourceData};
use rspack_sources::Source;
use rspack_util::fx_dashmap::FxDashMap;
use rustc_hash::FxHashMap as HashMap;
use tokio::sync::mpsc::UnboundedSender;
use tracing::instrument;
Expand Down Expand Up @@ -36,7 +37,8 @@ pub struct PluginDriver {
pub plugins: Vec<Box<dyn Plugin>>,
pub resolver_factory: Arc<ResolverFactory>,
// pub registered_parser: HashMap<ModuleType, BoxedParser>,
pub registered_parser_and_generator_builder: HashMap<ModuleType, BoxedParserAndGeneratorBuilder>,
pub registered_parser_and_generator_builder:
FxDashMap<ModuleType, BoxedParserAndGeneratorBuilder>,
/// Collecting error generated by plugin phase, e.g., `Syntax Error`
pub diagnostics: Arc<Mutex<Vec<Diagnostic>>>,
}
Expand All @@ -60,7 +62,7 @@ impl PluginDriver {
resolver_factory: Arc<ResolverFactory>,
compiler_hooks: &mut CompilerHooks,
) -> (Arc<Self>, Arc<CompilerOptions>) {
let mut registered_parser_and_generator_builder = HashMap::default();
let mut registered_parser_and_generator_builder = FxDashMap::default();
let mut apply_context = ApplyContext {
registered_parser_and_generator_builder: &mut registered_parser_and_generator_builder,
compiler_hooks,
Expand Down
23 changes: 21 additions & 2 deletions crates/rspack_plugin_css/src/plugin/impl_plugin_for_css_plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ impl Plugin for CssPlugin {
) -> rspack_core::PluginContentHashHookOutput {
let compilation = &args.compilation;
let chunk = compilation.chunk_by_ukey.expect_get(&args.chunk_ukey);
let ordered_modules = Self::get_ordered_chunk_css_modules(
let (ordered_modules, _) = Self::get_ordered_chunk_css_modules(
chunk,
&compilation.chunk_graph,
&compilation.module_graph,
Expand Down Expand Up @@ -219,13 +219,32 @@ impl Plugin for CssPlugin {
return Ok(vec![].with_empty_diagnostic());
}

let ordered_css_modules = Self::get_ordered_chunk_css_modules(
let (ordered_css_modules, _conflicts) = Self::get_ordered_chunk_css_modules(
chunk,
&compilation.chunk_graph,
&compilation.module_graph,
compilation,
);

// if let Some(conflicts) = conflicts {
// for conflict in conflicts {
// let chunk = compilation.chunk_by_ukey.expect_get(&conflict.chunk);
// let warning = Diagnostic::warn(
// "css order conflicts".into(),
// format!(
// "chunk {}",
// chunk
// .name
// .as_ref()
// .map(|s| s.as_str())
// .or_else(|| { chunk.id.as_ref().map(|s| s.as_str()) })
// .unwrap_or(""),
// ),
// );
// compilation.push_diagnostic(warning);
// }
// }

// Prevent generating css files for chunks which don't contain css modules.
if ordered_css_modules.is_empty() {
return Ok(vec![].with_empty_diagnostic());
Expand Down
Loading

0 comments on commit ea0d21b

Please sign in to comment.