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 Dec 25, 2023
1 parent c3c21f1 commit 4986da4
Show file tree
Hide file tree
Showing 45 changed files with 2,295 additions and 44 deletions.
30 changes: 30 additions & 0 deletions Cargo.lock

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

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

export function cleanupGlobalTrace(): void
Expand Down Expand Up @@ -742,6 +743,16 @@ export interface RawCrossOriginLoading {
boolPayload?: boolean
}

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

export interface RawCssModulesConfig {
localsConvention: "asIs" | "camelCase" | "camelCaseOnly" | "dashes" | "dashesOnly"
localIdentName: string
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 @@ -26,6 +26,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
16 changes: 13 additions & 3 deletions crates/rspack_binding_options/src/options/raw_builtins/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
mod raw_banner;
mod raw_copy;
mod raw_css_extract;
mod raw_html;
mod raw_limit_chunk_count;
mod raw_mf;
Expand Down Expand Up @@ -57,15 +58,16 @@ use rspack_plugin_wasm::{enable_wasm_loading_plugin, AsyncWasmPlugin};
use rspack_plugin_web_worker_template::web_worker_template_plugin;
use rspack_plugin_worker::WorkerPlugin;

use self::raw_mf::{
RawConsumeSharedPluginOptions, RawContainerReferencePluginOptions, RawProvideOptions,
};
pub use self::{
raw_banner::RawBannerPluginOptions, raw_copy::RawCopyRspackPluginOptions,
raw_html::RawHtmlRspackPluginOptions, raw_limit_chunk_count::RawLimitChunkCountPluginOptions,
raw_mf::RawContainerPluginOptions, raw_progress::RawProgressPluginOptions,
raw_swc_js_minimizer::RawSwcJsMinimizerRspackPluginOptions,
};
use self::{
raw_css_extract::RawCssExtractPluginOption,
raw_mf::{RawConsumeSharedPluginOptions, RawContainerReferencePluginOptions, RawProvideOptions},
};
use crate::{
RawEntryPluginOptions, RawExternalItemWrapper, RawExternalsPluginOptions,
RawHttpExternalsRspackPluginOptions, RawSourceMapDevToolPluginOptions, RawSplitChunksOptions,
Expand Down Expand Up @@ -131,6 +133,7 @@ pub enum BuiltinPluginName {
HtmlRspackPlugin,
SwcJsMinimizerRspackPlugin,
SwcCssMinimizerRspackPlugin,
CssExtractPlugin,
}

#[napi(object)]
Expand Down Expand Up @@ -358,6 +361,13 @@ impl BuiltinPlugin {
.boxed();
plugins.push(plugin);
}
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,38 @@
use std::collections::HashMap;

use napi_derive::napi;
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,
}

impl From<RawCssExtractPluginOption> for CssExtractOptions {
fn from(value: RawCssExtractPluginOption) -> Self {
Self {
filename: value.filename,
chunk_filename: 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,
}
}
}
2 changes: 1 addition & 1 deletion crates/rspack_core/src/compiler/compilation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2192,7 +2192,6 @@ impl Compilation {
// restore code_generation_results and chunk_graph
let mut codegen_results =
std::mem::replace(&mut self.code_generation_results, old_codegen_results);
self.chunk_graph = old_chunk_graph;

for runtime_id in &runtime_modules {
let runtime_module = self
Expand All @@ -2210,6 +2209,7 @@ impl Compilation {
}

// clear side effects stuff we caused
self.chunk_graph = old_chunk_graph;
self.chunk_by_ukey = old_chunk_by_ukey;
self.chunk_group_by_ukey.remove(&entry_ukey);
self.bailout_module_identifiers = old_bailout_module_identifiers;
Expand Down
7 changes: 3 additions & 4 deletions crates/rspack_core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ pub enum SourceType {
Remote,
ShareInit,
ConsumeShared,
Custom(Ustr),
#[default]
Unknown,
}
Expand All @@ -123,6 +124,7 @@ 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),
}
}
}
Expand All @@ -142,10 +144,7 @@ impl TryFrom<&str> for SourceType {
"consume-shared" => Ok(Self::ConsumeShared),
"unknown" => Ok(Self::Unknown),

_ => {
use rspack_error::internal_error;
Err(internal_error!("invalid source type: {value}"))
}
other => Ok(SourceType::Custom(other.into())),
}
}
}
Expand Down
3 changes: 1 addition & 2 deletions crates/rspack_core/src/plugin/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -596,8 +596,7 @@ pub type BoxedParserAndGeneratorBuilder =

#[derive(Default)]
pub struct ApplyContext {
pub(crate) registered_parser_and_generator_builder:
DashMap<ModuleType, BoxedParserAndGeneratorBuilder>,
pub registered_parser_and_generator_builder: DashMap<ModuleType, BoxedParserAndGeneratorBuilder>,
}

impl ApplyContext {
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 @@ -5,6 +5,7 @@ use std::{

use rspack_error::{Diagnostic, Result};
use rspack_loader_runner::ResourceData;
use rspack_util::fx_dashmap::FxDashMap;
use rustc_hash::FxHashMap as HashMap;
use tokio::sync::mpsc::UnboundedSender;
use tracing::instrument;
Expand Down Expand Up @@ -34,7 +35,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 Down Expand Up @@ -75,7 +77,7 @@ impl PluginDriver {
.into_iter()
.collect::<Vec<_>>()
})
.collect::<HashMap<ModuleType, BoxedParserAndGeneratorBuilder>>();
.collect::<FxDashMap<ModuleType, BoxedParserAndGeneratorBuilder>>();

let options = Arc::new(options);

Expand Down
42 changes: 42 additions & 0 deletions crates/rspack_plugin_extract_css/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
[package]
edition = "2021"
license = "MIT"
name = "rspack_plugin_extract_css"
repository = "https://github.com/web-infra-dev/rspack"
version = "0.1.0"

[dependencies]
anyhow = { workspace = true }
async-trait = { workspace = true }
bitflags = { workspace = true }
heck = "0.4.1"
indexmap = { workspace = true }
once_cell = { workspace = true }
rayon = { workspace = true }
regex = { workspace = true }
rkyv = { workspace = true, features = ["indexmap", "validation"] }
rspack_core = { path = "../rspack_core" }
rspack_error = { path = "../rspack_error" }
rspack_hash = { path = "../rspack_hash" }
rspack_identifier = { path = "../rspack_identifier" }
rspack_plugin_runtime = { path = "../rspack_plugin_runtime" }
rustc-hash = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
sugar_path = { workspace = true }
swc_core = { workspace = true, features = [
"css_ast",
"css_codegen",
"css_parser",
"css_utils",
"css_visit",
"css_visit_path",
"css_compat",
"css_modules",
"css_prefixer",
"css_minifier",
] }
tokio = { workspace = true }
tracing = { workspace = true }
urlencoding = "2.1.2"
ustr = { workspace = true }
22 changes: 22 additions & 0 deletions crates/rspack_plugin_extract_css/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
MIT License

Copyright (c) 2022-present Bytedance, Inc. and its affiliates.


Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
74 changes: 74 additions & 0 deletions crates/rspack_plugin_extract_css/src/css_dependency.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
use rspack_core::{
AsContextDependency, AsDependencyTemplate, ConnectionState, Dependency, DependencyCategory,
DependencyId, ModuleDependency, ModuleGraph, ModuleIdentifier,
};
use rustc_hash::FxHashSet;

use crate::css_module::DEPENDENCY_TYPE;

#[derive(Debug, Clone)]
pub struct CssDependency {
pub id: DependencyId,
pub identifier: String,
pub content: String,
pub context: String,
pub media: String,
pub supports: String,
pub source_map: String,
}

impl CssDependency {
pub(crate) fn new(
identifier: String,
content: String,
context: String,
media: String,
supports: String,
source_map: String,
) -> Self {
Self {
id: DependencyId::new(),
identifier,
content,
context,
media,
supports,
source_map,
}
}
}

impl AsDependencyTemplate for CssDependency {}
impl AsContextDependency for CssDependency {}

impl Dependency for CssDependency {
fn dependency_debug_name(&self) -> &'static str {
"mini-extract-css-dependency"
}

fn id(&self) -> &DependencyId {
&self.id
}

fn dependency_type(&self) -> &rspack_core::DependencyType {
&DEPENDENCY_TYPE
}

fn category(&self) -> &DependencyCategory {
&DependencyCategory::Unknown
}

fn get_module_evaluation_side_effects_state(
&self,
_module_graph: &ModuleGraph,
_module_chain: &mut FxHashSet<ModuleIdentifier>,
) -> ConnectionState {
ConnectionState::TransitiveOnly
}
}

impl ModuleDependency for CssDependency {
fn request(&self) -> &str {
&self.identifier
}
}
Loading

0 comments on commit 4986da4

Please sign in to comment.