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

feat: support dynamic entry #6393

Merged
merged 13 commits into from
Apr 29, 2024
Merged
Show file tree
Hide file tree
Changes from 11 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
13 changes: 13 additions & 0 deletions Cargo.lock

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

11 changes: 11 additions & 0 deletions crates/node_binding/binding.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ export enum BuiltinPluginName {
IgnorePlugin = 'IgnorePlugin',
ProgressPlugin = 'ProgressPlugin',
EntryPlugin = 'EntryPlugin',
DynamicEntryPlugin = 'DynamicEntryPlugin',
ExternalsPlugin = 'ExternalsPlugin',
NodeTargetPlugin = 'NodeTargetPlugin',
ElectronTargetPlugin = 'ElectronTargetPlugin',
Expand Down Expand Up @@ -795,6 +796,16 @@ export interface RawCssParserOptions {
namedExports?: boolean
}

export interface RawDynamicEntryPluginOptions {
context: string
entry: () => Promise<RawEntryDynamicResult[]>
}

export interface RawEntryDynamicResult {
import: Array<string>
options: RawEntryOptions
}

export interface RawEntryOptions {
name?: string
runtime?: false | 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 @@ -31,6 +31,7 @@ rspack_plugin_banner = { path = "../rspack_plugin_banner" }
rspack_plugin_copy = { path = "../rspack_plugin_copy" }
rspack_plugin_css = { path = "../rspack_plugin_css" }
rspack_plugin_devtool = { path = "../rspack_plugin_devtool" }
rspack_plugin_dynamic_entry = { path = "../rspack_plugin_dynamic_entry" }
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" }
Expand Down
2 changes: 2 additions & 0 deletions crates/rspack_binding_options/src/options/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use rspack_core::{
mod raw_builtins;
mod raw_cache;
mod raw_devtool;
mod raw_dynamic_entry;
mod raw_entry;
mod raw_experiments;
mod raw_external;
Expand All @@ -23,6 +24,7 @@ mod raw_stats;
pub use raw_builtins::*;
pub use raw_cache::*;
pub use raw_devtool::*;
pub use raw_dynamic_entry::*;
pub use raw_entry::*;
pub use raw_experiments::*;
pub use raw_external::*;
Expand Down
15 changes: 12 additions & 3 deletions crates/rspack_binding_options/src/options/raw_builtins/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ use rspack_plugin_devtool::{
SourceMapDevToolModuleOptionsPluginOptions, SourceMapDevToolPlugin,
SourceMapDevToolPluginOptions,
};
use rspack_plugin_dynamic_entry::DynamicEntryPlugin;
use rspack_plugin_ensure_chunk_conditions::EnsureChunkConditionsPlugin;
use rspack_plugin_entry::EntryPlugin;
use rspack_plugin_externals::{
Expand Down Expand Up @@ -81,9 +82,9 @@ use self::{
};
use crate::{
plugins::{CssExtractRspackAdditionalDataPlugin, JsLoaderResolverPlugin},
JsLoaderRunner, RawEntryPluginOptions, RawEvalDevToolModulePluginOptions, RawExternalItemWrapper,
RawExternalsPluginOptions, RawHttpExternalsRspackPluginOptions, RawSourceMapDevToolPluginOptions,
RawSplitChunksOptions,
JsLoaderRunner, RawDynamicEntryPluginOptions, RawEntryPluginOptions,
RawEvalDevToolModulePluginOptions, RawExternalItemWrapper, RawExternalsPluginOptions,
RawHttpExternalsRspackPluginOptions, RawSourceMapDevToolPluginOptions, RawSplitChunksOptions,
};

#[napi(string_enum)]
Expand All @@ -96,6 +97,7 @@ pub enum BuiltinPluginName {
IgnorePlugin,
ProgressPlugin,
EntryPlugin,
DynamicEntryPlugin,
ExternalsPlugin,
NodeTargetPlugin,
ElectronTargetPlugin,
Expand Down Expand Up @@ -205,6 +207,13 @@ impl BuiltinPlugin {
let plugin = EntryPlugin::new(context, entry_request, options).boxed();
plugins.push(plugin);
}
BuiltinPluginName::DynamicEntryPlugin => {
let plugin = DynamicEntryPlugin::new(
downcast_into::<RawDynamicEntryPluginOptions>(self.options)?.into(),
)
.boxed();
plugins.push(plugin);
}
BuiltinPluginName::ExternalsPlugin => {
let plugin_options = downcast_into::<RawExternalsPluginOptions>(self.options)?;
let externals = plugin_options
Expand Down
46 changes: 46 additions & 0 deletions crates/rspack_binding_options/src/options/raw_dynamic_entry.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
use napi_derive::napi;
use rspack_napi::threadsafe_function::ThreadsafeFunction;
use rspack_plugin_dynamic_entry::{DynamicEntryPluginOptions, EntryDynamicResult};

use crate::RawEntryOptions;

#[derive(Debug)]
#[napi(object)]
pub struct RawEntryDynamicResult {
pub import: Vec<String>,
pub options: RawEntryOptions,
}

pub type RawEntryDynamic = ThreadsafeFunction<(), Vec<RawEntryDynamicResult>>;

#[derive(Debug)]
#[napi(object, object_to_js = false)]
pub struct RawDynamicEntryPluginOptions {
pub context: String,
#[napi(ts_type = "() => Promise<RawEntryDynamicResult[]>")]
pub entry: RawEntryDynamic,
}

impl From<RawDynamicEntryPluginOptions> for DynamicEntryPluginOptions {
fn from(opts: RawDynamicEntryPluginOptions) -> Self {
Self {
context: opts.context.into(),
entry: Box::new(move || {
let f = opts.entry.clone();
Box::pin(async move {
let raw_result = f.call(()).await?;
let result = raw_result
.into_iter()
.map(
|RawEntryDynamicResult { import, options }| EntryDynamicResult {
import,
options: options.into(),
},
)
.collect::<Vec<_>>();
Ok(result)
})
}),
}
}
}
16 changes: 16 additions & 0 deletions crates/rspack_plugin_dynamic_entry/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
[package]
edition = "2021"
license = "MIT"
name = "rspack_plugin_dynamic_entry"
repository = "https://github.com/web-infra-dev/rspack"
version = "0.1.0"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
async-trait = { workspace = true }
derivative = { workspace = true }
futures = { workspace = true }
rspack_core = { path = "../rspack_core" }
rspack_error = { path = "../rspack_error" }
rspack_hook = { path = "../rspack_hook" }
22 changes: 22 additions & 0 deletions crates/rspack_plugin_dynamic_entry/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.
81 changes: 81 additions & 0 deletions crates/rspack_plugin_dynamic_entry/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
use async_trait::async_trait;
use derivative::Derivative;
use futures::future::BoxFuture;
use rspack_core::{
ApplyContext, BoxDependency, Compilation, CompilationParams, CompilerCompilation, CompilerMake,
CompilerOptions, Context, DependencyType, EntryDependency, EntryOptions, MakeParam, Plugin,
PluginContext,
};
use rspack_error::Result;
use rspack_hook::{plugin, plugin_hook};

pub struct EntryDynamicResult {
pub import: Vec<String>,
pub options: EntryOptions,
}

type EntryDynamic =
Box<dyn for<'a> Fn() -> BoxFuture<'static, Result<Vec<EntryDynamicResult>>> + Sync + Send>;

pub struct DynamicEntryPluginOptions {
pub context: Context,
pub entry: EntryDynamic,
}

#[plugin]
#[derive(Derivative)]
#[derivative(Debug)]
pub struct DynamicEntryPlugin {
context: Context,
#[derivative(Debug = "ignore")]
entry: EntryDynamic,
}

impl DynamicEntryPlugin {
pub fn new(options: DynamicEntryPluginOptions) -> Self {
Self::new_inner(options.context, options.entry)
}
}

#[plugin_hook(CompilerCompilation for DynamicEntryPlugin)]
async fn compilation(
&self,
compilation: &mut Compilation,
params: &mut CompilationParams,
) -> Result<()> {
compilation.set_dependency_factory(DependencyType::Entry, params.normal_module_factory.clone());
Ok(())
}

#[plugin_hook(CompilerMake for DynamicEntryPlugin)]
async fn make(&self, compilation: &mut Compilation, params: &mut Vec<MakeParam>) -> Result<()> {
let entry_fn = &self.entry;
let decs = entry_fn().await?;
for EntryDynamicResult { import, options } in decs {
for entry in import {
let dependency: BoxDependency = Box::new(EntryDependency::new(entry, self.context.clone()));
let dependency_id = *dependency.id();
compilation.add_entry(dependency, options.clone()).await?;

params.push(MakeParam::new_force_build_dep_param(dependency_id, None));
}
}
Ok(())
}

#[async_trait]
impl Plugin for DynamicEntryPlugin {
fn apply(
&self,
ctx: PluginContext<&mut ApplyContext>,
_options: &mut CompilerOptions,
) -> Result<()> {
ctx
.context
.compiler_hooks
.compilation
.tap(compilation::new(self));
ctx.context.compiler_hooks.make.tap(make::new(self));
Ok(())
}
}
24 changes: 23 additions & 1 deletion packages/rspack/etc/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ import { RawBundlerInfoPluginOptions } from '@rspack/binding';
import { RawCopyPattern } from '@rspack/binding';
import { RawCopyRspackPluginOptions } from '@rspack/binding';
import type { RawCssExtractPluginOption } from '@rspack/binding';
import { RawDynamicEntryPluginOptions } from '@rspack/binding';
import { RawEntryOptions } from '@rspack/binding';
import { RawEntryPluginOptions } from '@rspack/binding';
import { RawExternalsPluginOptions } from '@rspack/binding';
import { RawFuncUseCtx } from '@rspack/binding';
Expand Down Expand Up @@ -1909,6 +1911,17 @@ export type DevtoolNamespace = z.infer<typeof devtoolNamespace>;
// @public (undocumented)
const devtoolNamespace: z.ZodString;

// @public (undocumented)
const DynamicEntryPlugin: {
new (context: string, entry: EntryDynamicNormalized): {
name: BuiltinPluginName;
_options: RawDynamicEntryPluginOptions;
affectedHooks: "done" | "compilation" | "make" | "compile" | "emit" | "afterEmit" | "invalid" | "thisCompilation" | "afterDone" | "normalModuleFactory" | "contextModuleFactory" | "initialize" | "shouldEmit" | "infrastructureLog" | "beforeRun" | "run" | "assetEmitted" | "failed" | "shutdown" | "watchRun" | "watchClose" | "environment" | "afterEnvironment" | "afterPlugins" | "afterResolvers" | "beforeCompile" | "afterCompile" | "finishMake" | "entryOption" | undefined;
raw(): BuiltinPlugin;
apply(compiler: Compiler_2): void;
};
};

// @public (undocumented)
interface Electron {
// (undocumented)
Expand Down Expand Up @@ -2446,6 +2459,9 @@ export interface EntryDescriptionNormalized {
runtime?: EntryRuntime;
}

// @public (undocumented)
export type EntryDynamicNormalized = () => Promise<EntryStaticNormalized>;

// @public (undocumented)
export type EntryFilename = z.infer<typeof entryFilename>;

Expand All @@ -2459,7 +2475,7 @@ export type EntryItem = z.infer<typeof entryItem>;
const entryItem: z.ZodUnion<[z.ZodString, z.ZodArray<z.ZodString, "many">]>;

// @public (undocumented)
export type EntryNormalized = EntryStaticNormalized;
export type EntryNormalized = EntryDynamicNormalized | EntryStaticNormalized;

// @public (undocumented)
export type EntryObject = z.infer<typeof entryObject>;
Expand Down Expand Up @@ -3714,6 +3730,9 @@ export const getNormalizedRspackOptions: (config: RspackOptions) => RspackOption
// @public (undocumented)
export function getRawChunkLoading(chunkLoading: ChunkLoading): string;

// @public (undocumented)
function getRawEntryOptions(entry: EntryOptions): RawEntryOptions;

// @public (undocumented)
export function getRawLibrary(library: LibraryOptions): RawLibraryOptions;

Expand Down Expand Up @@ -5939,8 +5958,10 @@ declare namespace oldBuiltins {
IgnorePlugin,
ProgressPluginArgument,
ProgressPlugin,
getRawEntryOptions,
EntryOptions,
EntryPlugin,
DynamicEntryPlugin,
ExternalsPlugin,
NodeTargetPlugin,
ElectronTargetPlugin,
Expand Down Expand Up @@ -7945,6 +7966,7 @@ declare namespace rspackExports {
SwcLoaderTsParserConfig,
SwcLoaderTransformConfig,
getNormalizedRspackOptions,
EntryDynamicNormalized,
EntryNormalized,
EntryStaticNormalized,
EntryDescriptionNormalized,
Expand Down
35 changes: 35 additions & 0 deletions packages/rspack/src/builtin-plugin/DynamicEntryPlugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import {
BuiltinPluginName,
RawDynamicEntryPluginOptions
} from "@rspack/binding";
import { create } from "./base";
import { EntryDynamicNormalized } from "../config";
import EntryOptionPlugin from "../lib/EntryOptionPlugin";
import { getRawEntryOptions } from "./EntryPlugin";

export const DynamicEntryPlugin = create(
BuiltinPluginName.DynamicEntryPlugin,
(
context: string,
entry: EntryDynamicNormalized
): RawDynamicEntryPluginOptions => {
return {
context,
entry: async () => {
const result = await entry();
return Object.entries(result).map(([name, desc]) => {
const options = EntryOptionPlugin.entryDescriptionToOptions(
{} as any,
name,
desc
);
return {
import: desc.import!,
options: getRawEntryOptions(options)
};
});
}
};
},
"make"
);
Loading
Loading