Skip to content

Commit

Permalink
fix: runtimeChunk should control all entries' runtime (#6388)
Browse files Browse the repository at this point in the history
ahabhgk authored Apr 29, 2024

Verified

This commit was signed with the committer’s verified signature. The key has expired.
weihanglo Weihang Lo
1 parent ec3c0df commit 6d8ec18
Showing 52 changed files with 625 additions and 123 deletions.
11 changes: 11 additions & 0 deletions Cargo.lock

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

13 changes: 11 additions & 2 deletions crates/node_binding/binding.d.ts
Original file line number Diff line number Diff line change
@@ -161,6 +161,7 @@ export enum BuiltinPluginName {
ModuleConcatenationPlugin = 'ModuleConcatenationPlugin',
CssModulesPlugin = 'CssModulesPlugin',
APIPlugin = 'APIPlugin',
RuntimeChunkPlugin = 'RuntimeChunkPlugin',
HttpExternalsRspackPlugin = 'HttpExternalsRspackPlugin',
CopyRspackPlugin = 'CopyRspackPlugin',
HtmlRspackPlugin = 'HtmlRspackPlugin',
@@ -713,7 +714,7 @@ export interface RawContainerPluginOptions {
name: string
shareScope: string
library: RawLibraryOptions
runtime?: string
runtime?: false | string
filename?: string
exposes: Array<RawExposeOptions>
enhanced: boolean
@@ -796,7 +797,7 @@ export interface RawCssParserOptions {

export interface RawEntryOptions {
name?: string
runtime?: string
runtime?: false | string
chunkLoading?: string
asyncChunks?: boolean
publicPath?: string
@@ -1245,6 +1246,14 @@ export interface RawRuleSetLogicalConditions {
not?: RawRuleSetCondition
}

export interface RawRuntimeChunkNameFnCtx {
name: string
}

export interface RawRuntimeChunkOptions {
name: string | ((entrypoint: { name: string }) => string)
}

export interface RawSnapshotOptions {
resolve: RawSnapshotStrategy
module: RawSnapshotStrategy
1 change: 1 addition & 0 deletions crates/rspack_binding_options/Cargo.toml
Original file line number Diff line number Diff line change
@@ -48,6 +48,7 @@ rspack_plugin_progress = { path = "../rspack_plugin_progress" }
rspack_plugin_real_content_hash = { path = "../rspack_plugin_real_content_hash" }
rspack_plugin_remove_empty_chunks = { path = "../rspack_plugin_remove_empty_chunks" }
rspack_plugin_runtime = { path = "../rspack_plugin_runtime" }
rspack_plugin_runtime_chunk = { path = "../rspack_plugin_runtime_chunk" }
rspack_plugin_schemes = { path = "../rspack_plugin_schemes" }
rspack_plugin_split_chunks = { path = "../rspack_plugin_split_chunks" }
rspack_plugin_swc_css_minimizer = { path = "../rspack_plugin_swc_css_minimizer" }
8 changes: 8 additions & 0 deletions crates/rspack_binding_options/src/options/raw_builtins/mod.rs
Original file line number Diff line number Diff line change
@@ -7,6 +7,7 @@ mod raw_ignore;
mod raw_limit_chunk_count;
mod raw_mf;
mod raw_progress;
mod raw_runtime_chunk;
mod raw_swc_js_minimizer;
mod raw_to_be_deprecated;

@@ -56,6 +57,7 @@ use rspack_plugin_runtime::{
enable_chunk_loading_plugin, ArrayPushCallbackChunkFormatPlugin, BundlerInfoPlugin,
ChunkPrefetchPreloadPlugin, CommonJsChunkFormatPlugin, ModuleChunkFormatPlugin, RuntimePlugin,
};
use rspack_plugin_runtime_chunk::RuntimeChunkPlugin;
use rspack_plugin_schemes::{DataUriPlugin, FileUriPlugin};
use rspack_plugin_swc_css_minimizer::SwcCssMinimizerRspackPlugin;
use rspack_plugin_swc_js_minimizer::SwcJsMinimizerRspackPlugin;
@@ -75,6 +77,7 @@ use self::{
raw_bundle_info::{RawBundlerInfoModeWrapper, RawBundlerInfoPluginOptions},
raw_css_extract::RawCssExtractPluginOption,
raw_mf::{RawConsumeSharedPluginOptions, RawContainerReferencePluginOptions, RawProvideOptions},
raw_runtime_chunk::RawRuntimeChunkOptions,
};
use crate::{
plugins::{CssExtractRspackAdditionalDataPlugin, JsLoaderResolverPlugin},
@@ -141,6 +144,7 @@ pub enum BuiltinPluginName {
ModuleConcatenationPlugin,
CssModulesPlugin,
APIPlugin,
RuntimeChunkPlugin,

// rspack specific plugins
// naming format follow XxxRspackPlugin
@@ -383,6 +387,10 @@ impl BuiltinPlugin {
}
BuiltinPluginName::CssModulesPlugin => plugins.push(CssPlugin::default().boxed()),
BuiltinPluginName::APIPlugin => plugins.push(APIPlugin::default().boxed()),
BuiltinPluginName::RuntimeChunkPlugin => plugins.push(
RuntimeChunkPlugin::new(downcast_into::<RawRuntimeChunkOptions>(self.options)?.into())
.boxed(),
),

// rspack specific plugins
BuiltinPluginName::HttpExternalsRspackPlugin => {
Original file line number Diff line number Diff line change
@@ -7,15 +7,16 @@ use rspack_plugin_mf::{
ContainerReferencePluginOptions, ExposeOptions, ProvideOptions, ProvideVersion, RemoteOptions,
};

use crate::RawLibraryOptions;
use crate::{RawEntryRuntime, RawEntryRuntimeWrapper, RawLibraryOptions};

#[derive(Debug)]
#[napi(object)]
pub struct RawContainerPluginOptions {
pub name: String,
pub share_scope: String,
pub library: RawLibraryOptions,
pub runtime: Option<String>,
#[napi(ts_type = "false | string")]
pub runtime: Option<RawEntryRuntime>,
pub filename: Option<String>,
pub exposes: Vec<RawExposeOptions>,
pub enhanced: bool,
@@ -27,7 +28,7 @@ impl From<RawContainerPluginOptions> for ContainerPluginOptions {
name: value.name,
share_scope: value.share_scope,
library: value.library.into(),
runtime: value.runtime,
runtime: value.runtime.map(|r| RawEntryRuntimeWrapper(r).into()),
filename: value.filename.map(|f| f.into()),
exposes: value.exposes.into_iter().map(|e| e.into()).collect(),
enhanced: value.enhanced,
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
use napi::Either;
use napi_derive::napi;
use rspack_napi::threadsafe_function::ThreadsafeFunction;
use rspack_plugin_runtime_chunk::{RuntimeChunkName, RuntimeChunkOptions};

#[napi(object, object_to_js = false)]
pub struct RawRuntimeChunkOptions {
#[napi(ts_type = "string | ((entrypoint: { name: string }) => string)")]
pub name: RawRuntimeChunkName,
}

impl From<RawRuntimeChunkOptions> for RuntimeChunkOptions {
fn from(value: RawRuntimeChunkOptions) -> Self {
Self {
name: RawRuntimeChunkNameWrapper(value.name).into(),
}
}
}

type RawRuntimeChunkName = Either<String, ThreadsafeFunction<RawRuntimeChunkNameFnCtx, String>>;
struct RawRuntimeChunkNameWrapper(RawRuntimeChunkName);

#[napi(object)]
pub struct RawRuntimeChunkNameFnCtx {
pub name: String,
}

impl From<RawRuntimeChunkNameWrapper> for RuntimeChunkName {
fn from(value: RawRuntimeChunkNameWrapper) -> Self {
match value.0 {
Either::A(s) => {
if s == "single" {
Self::Single
} else if s == "multiple" {
Self::Multiple
} else {
Self::String(s)
}
}
Either::B(f) => RuntimeChunkName::Fn(Box::new(move |name| {
let f = f.clone();
Box::pin(async move {
f.call(RawRuntimeChunkNameFnCtx {
name: name.to_string(),
})
.await
})
})),
}
}
}
23 changes: 20 additions & 3 deletions crates/rspack_binding_options/src/options/raw_entry.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use napi::Either;
use napi_derive::napi;
use rspack_core::EntryOptions;
use rspack_core::{EntryOptions, EntryRuntime};

use crate::RawLibraryOptions;

@@ -11,11 +12,27 @@ pub struct RawEntryPluginOptions {
pub options: RawEntryOptions,
}

pub type RawEntryRuntime = Either<bool, String>;
pub struct RawEntryRuntimeWrapper(pub RawEntryRuntime);

impl From<RawEntryRuntimeWrapper> for EntryRuntime {
fn from(value: RawEntryRuntimeWrapper) -> Self {
match value.0 {
Either::A(b) => {
assert!(!b, "RawEntryRuntime should be false or string");
Self::False
}
Either::B(s) => Self::String(s),
}
}
}

#[derive(Debug)]
#[napi(object)]
pub struct RawEntryOptions {
pub name: Option<String>,
pub runtime: Option<String>,
#[napi(ts_type = "false | string")]
pub runtime: Option<RawEntryRuntime>,
pub chunk_loading: Option<String>,
pub async_chunks: Option<bool>,
pub public_path: Option<String>,
@@ -29,7 +46,7 @@ impl From<RawEntryOptions> for EntryOptions {
fn from(value: RawEntryOptions) -> Self {
Self {
name: value.name,
runtime: value.runtime,
runtime: value.runtime.map(|r| RawEntryRuntimeWrapper(r).into()),
chunk_loading: value.chunk_loading.as_deref().map(Into::into),
async_chunks: value.async_chunks,
public_path: value.public_path.map(Into::into),
13 changes: 5 additions & 8 deletions crates/rspack_core/src/build_chunk_graph/code_splitter.rs
Original file line number Diff line number Diff line change
@@ -14,7 +14,7 @@ use crate::{
add_connection_states, assign_depth, assign_depths, get_entry_runtime,
AsyncDependenciesBlockIdentifier, ChunkGroup, ChunkGroupKind, ChunkGroupOptions, ChunkGroupUkey,
ChunkLoading, ChunkUkey, Compilation, ConnectionId, ConnectionState, DependenciesBlock,
GroupOptions, Logger, ModuleGraph, ModuleIdentifier, RuntimeSpec,
EntryRuntime, GroupOptions, Logger, ModuleGraph, ModuleIdentifier, RuntimeSpec,
};

#[derive(Debug, Clone)]
@@ -302,7 +302,7 @@ impl<'me> CodeSplitter<'me> {
cgi
};

if options.depend_on.is_none() && options.runtime.is_none() {
if options.depend_on.is_none() && !matches!(&options.runtime, Some(EntryRuntime::String(_))) {
entrypoint.set_runtime_chunk(chunk.ukey);
}
entrypoint.set_entry_point_chunk(chunk.ukey);
@@ -466,7 +466,7 @@ Remove the 'runtime' option from the entrypoint."
entry_point.add_parent(parent);
}
}
} else if let Some(runtime) = &options.runtime {
} else if let Some(EntryRuntime::String(runtime)) = &options.runtime {
let ukey = self
.compilation
.entrypoints
@@ -1063,11 +1063,8 @@ Or do you want to use the entrypoints '{name}' and '{runtime}' independently on

let cgi = ChunkGroupInfo::new(
entrypoint.ukey,
RuntimeSpec::from_iter([entry_options
.runtime
.as_deref()
.expect("should have runtime for AsyncEntrypoint")
.into()]),
RuntimeSpec::from_entry_options(&entry_options)
.expect("should have runtime for AsyncEntrypoint"),
entry_options
.chunk_loading
.as_ref()
2 changes: 1 addition & 1 deletion crates/rspack_core/src/chunk.rs
Original file line number Diff line number Diff line change
@@ -67,7 +67,7 @@ impl Chunk {
files: Default::default(),
auxiliary_files: Default::default(),
groups: Default::default(),
runtime: HashSet::default(),
runtime: RuntimeSpec::default(),
kind,
hash: None,
rendered_hash: None,
30 changes: 29 additions & 1 deletion crates/rspack_core/src/chunk_group.rs
Original file line number Diff line number Diff line change
@@ -326,7 +326,35 @@ impl ChunkGroupKind {
}
}

pub type EntryRuntime = String;
#[derive(Debug, Default, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub enum EntryRuntime {
String(String),
#[default]
False,
}

impl From<&str> for EntryRuntime {
fn from(value: &str) -> Self {
Self::String(value.to_owned())
}
}

impl From<String> for EntryRuntime {
fn from(value: String) -> Self {
Self::String(value)
}
}

impl EntryRuntime {
pub fn as_string(&self) -> Option<&str> {
match self {
EntryRuntime::String(s) => Some(s),
EntryRuntime::False => None,
}
}
}

// pub type EntryRuntime = String;

#[derive(Debug, Default, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub struct EntryOptions {
19 changes: 15 additions & 4 deletions crates/rspack_core/src/compiler/compilation.rs
Original file line number Diff line number Diff line change
@@ -46,6 +46,7 @@ pub type BuildDependency = (
Option<ModuleIdentifier>, /* parent module */
);

define_hook!(CompilationAddEntry: AsyncSeries(compilation: &mut Compilation, entry_name: Option<&str>));
define_hook!(CompilationBuildModule: AsyncSeries(module: &mut BoxModule));
define_hook!(CompilationStillValidModule: AsyncSeries(module: &mut BoxModule));
define_hook!(CompilationSucceedModule: AsyncSeries(module: &mut BoxModule));
@@ -77,6 +78,7 @@ define_hook!(CompilationAfterSeal: AsyncSeries(compilation: &mut Compilation));

#[derive(Debug, Default)]
pub struct CompilationHooks {
pub add_entry: CompilationAddEntryHook,
pub build_module: CompilationBuildModuleHook,
pub still_valid_module: CompilationStillValidModuleHook,
pub succeed_module: CompilationSucceedModuleHook,
@@ -344,11 +346,12 @@ impl Compilation {
import_var
}

pub fn add_entry(&mut self, entry: BoxDependency, options: EntryOptions) -> Result<()> {
pub async fn add_entry(&mut self, entry: BoxDependency, options: EntryOptions) -> Result<()> {
let entry_id = *entry.id();
let entry_name = options.name.clone();
self.get_module_graph_mut().add_dependency(entry);
if let Some(name) = options.name.clone() {
if let Some(data) = self.entries.get_mut(&name) {
if let Some(name) = &entry_name {
if let Some(data) = self.entries.get_mut(name) {
data.dependencies.push(entry_id);
data.options.merge(options)?;
} else {
@@ -357,11 +360,19 @@ impl Compilation {
include_dependencies: vec![],
options,
};
self.entries.insert(name, data);
self.entries.insert(name.to_owned(), data);
}
} else {
self.global_entry.dependencies.push(entry_id);
}

self
.plugin_driver
.clone()
.compilation_hooks
.add_entry
.call(self, entry_name.as_deref())
.await?;
Ok(())
}

Loading

2 comments on commit 6d8ec18

@rspack-bot
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📝 Ran ecosystem CI: Open

suite result
modernjs, self-hosted, Linux, ci ❌ failure
_selftest, ubuntu-latest ✅ success
nx, ubuntu-latest ✅ success
rspress, ubuntu-latest ✅ success
rsbuild, ubuntu-latest ✅ success
compat, ubuntu-latest ✅ success
examples, ubuntu-latest ✅ success

@rspack-bot
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📝 Benchmark detail: Open

Name Base (2024-04-29 ec3c0df) Current Change
10000_development-mode + exec 2.8 s ± 43 ms 2.77 s ± 43 ms -0.99 %
10000_development-mode_hmr + exec 690 ms ± 16 ms 706 ms ± 11 ms +2.35 %
10000_production-mode + exec 2.49 s ± 18 ms 2.56 s ± 35 ms +2.74 %
arco-pro_development-mode + exec 2.54 s ± 39 ms 2.48 s ± 73 ms -2.49 %
arco-pro_development-mode_hmr + exec 431 ms ± 2.6 ms 429 ms ± 1.5 ms -0.34 %
arco-pro_development-mode_hmr_intercept-plugin + exec 443 ms ± 2.5 ms 441 ms ± 3.5 ms -0.36 %
arco-pro_development-mode_intercept-plugin + exec 3.25 s ± 72 ms 3.26 s ± 95 ms +0.53 %
arco-pro_production-mode + exec 3.99 s ± 103 ms 3.96 s ± 59 ms -0.80 %
arco-pro_production-mode_intercept-plugin + exec 4.75 s ± 102 ms 4.77 s ± 95 ms +0.44 %
threejs_development-mode_10x + exec 2.08 s ± 23 ms 2.07 s ± 22 ms -0.49 %
threejs_development-mode_10x_hmr + exec 771 ms ± 32 ms 762 ms ± 6.6 ms -1.12 %
threejs_production-mode_10x + exec 5.26 s ± 54 ms 5.27 s ± 26 ms +0.15 %

Please sign in to comment.