Skip to content

Commit

Permalink
refactor: module executor should use separate plugin_driver
Browse files Browse the repository at this point in the history
  • Loading branch information
JSerFeng committed Sep 24, 2024
1 parent 1859fa8 commit 5d0cba7
Show file tree
Hide file tree
Showing 18 changed files with 113 additions and 22 deletions.
Original file line number Diff line number Diff line change
@@ -1,15 +1,10 @@
use rspack_core::{BoxPlugin, ChunkLoading, ChunkLoadingType, PluginExt};
use rspack_core::{BoxPlugin, PluginExt};
use rspack_plugin_javascript::JsPlugin;
use rspack_plugin_runtime::{
CommonJsChunkLoadingPlugin, RuntimePlugin, StartupChunkDependenciesPlugin,
};
use rspack_plugin_runtime::RuntimePlugin;

pub fn buildtime_plugins() -> Vec<BoxPlugin> {
vec![
RuntimePlugin::default().boxed(),
JsPlugin::default().boxed(),
// StartupChunkDependenciesPlugin::new(ChunkLoading::Enable(ChunkLoadingType::Require), false)
// .boxed(),
// CommonJsChunkLoadingPlugin::new(false).boxed(),
]
}
3 changes: 3 additions & 0 deletions crates/rspack_core/src/compiler/compilation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@ pub struct Compilation {
diagnostics: Vec<Diagnostic>,
logging: CompilationLogging,
pub plugin_driver: SharedPluginDriver,
pub buildtime_plugin_driver: SharedPluginDriver,
pub resolver_factory: Arc<ResolverFactory>,
pub loader_resolver_factory: Arc<ResolverFactory>,
pub named_chunks: HashMap<String, ChunkUkey>,
Expand Down Expand Up @@ -224,6 +225,7 @@ impl Compilation {
pub fn new(
options: Arc<CompilerOptions>,
plugin_driver: SharedPluginDriver,
buildtime_plugin_driver: SharedPluginDriver,
resolver_factory: Arc<ResolverFactory>,
loader_resolver_factory: Arc<ResolverFactory>,
records: Option<CompilationRecords>,
Expand Down Expand Up @@ -257,6 +259,7 @@ impl Compilation {
diagnostics: Default::default(),
logging: Default::default(),
plugin_driver,
buildtime_plugin_driver,
resolver_factory,
loader_resolver_factory,
named_chunks: Default::default(),
Expand Down
1 change: 1 addition & 0 deletions crates/rspack_core/src/compiler/hmr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ impl Compiler {
let mut new_compilation = Compilation::new(
self.options.clone(),
self.plugin_driver.clone(),
self.buildtime_plugin_driver.clone(),
self.resolver_factory.clone(),
self.loader_resolver_factory.clone(),
Some(records),
Expand Down
3 changes: 3 additions & 0 deletions crates/rspack_core/src/compiler/make/repair/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ use crate::{
pub struct MakeTaskContext {
// compilation info
pub plugin_driver: SharedPluginDriver,
pub buildtime_plugin_driver: SharedPluginDriver,
pub fs: Arc<dyn ReadableFileSystem>,
pub compiler_options: Arc<CompilerOptions>,
pub resolver_factory: Arc<ResolverFactory>,
Expand All @@ -37,6 +38,7 @@ impl MakeTaskContext {
pub fn new(compilation: &Compilation, artifact: MakeArtifact) -> Self {
Self {
plugin_driver: compilation.plugin_driver.clone(),
buildtime_plugin_driver: compilation.buildtime_plugin_driver.clone(),
compiler_options: compilation.options.clone(),
resolver_factory: compilation.resolver_factory.clone(),
loader_resolver_factory: compilation.loader_resolver_factory.clone(),
Expand All @@ -63,6 +65,7 @@ impl MakeTaskContext {
let mut compilation = Compilation::new(
self.compiler_options.clone(),
self.plugin_driver.clone(),
self.buildtime_plugin_driver.clone(),
self.resolver_factory.clone(),
self.loader_resolver_factory.clone(),
None,
Expand Down
2 changes: 2 additions & 0 deletions crates/rspack_core/src/compiler/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ impl Compiler {
compilation: Compilation::new(
options,
plugin_driver.clone(),
buildtime_plugin_driver.clone(),
resolver_factory.clone(),
loader_resolver_factory.clone(),
None,
Expand Down Expand Up @@ -159,6 +160,7 @@ impl Compiler {
Compilation::new(
self.options.clone(),
self.plugin_driver.clone(),
self.buildtime_plugin_driver.clone(),
self.resolver_factory.clone(),
self.loader_resolver_factory.clone(),
None,
Expand Down
2 changes: 1 addition & 1 deletion crates/rspack_core/src/compiler/module_executor/entry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ impl Task<MakeTaskContext> for EntryTask {
)
})
.clone(),
original_module_identifier: dep.original_module,
original_module_identifier: None,
original_module_source: None,
issuer: None,
issuer_layer: None,
Expand Down
16 changes: 8 additions & 8 deletions crates/rspack_core/src/compiler/module_executor/execute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,15 +70,16 @@ impl Task<MakeTaskContext> for ExecuteTask {
} = *self;

let mut compilation = context.transform_to_temp_compilation();
let main_compilation_plugin_driver = compilation.plugin_driver.clone();
compilation.plugin_driver = compilation.buildtime_plugin_driver.clone();

let id = EXECUTE_MODULE_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);

let mg = compilation.get_module_graph_mut();
let Some(entry_module_identifier) = mg.get_module_by_dependency_id(&entry_dep_id) else {
return Err(rspack_error::error!("entry module not found"));
};

let entry_module_identifier = entry_module_identifier.identifier();
let entry_module_identifier = mg
.get_module_by_dependency_id(&entry_dep_id)
.expect("should have module")
.identifier();
let mut queue = vec![entry_module_identifier];
let mut modules = IdentifierSet::default();

Expand Down Expand Up @@ -110,7 +111,7 @@ impl Task<MakeTaskContext> for ExecuteTask {
name: Some("build time".into()),
runtime: Some("runtime".into()),
chunk_loading: Some(crate::ChunkLoading::Disable),
async_chunks: None,
async_chunks: Some(false),
public_path,
base_uri,
filename: None,
Expand Down Expand Up @@ -211,8 +212,7 @@ impl Task<MakeTaskContext> for ExecuteTask {
}

let codegen_results = compilation.code_generation_results.clone();
let exports = compilation
.plugin_driver
let exports = main_compilation_plugin_driver
.compilation_hooks
.execute_module
.call(
Expand Down
1 change: 0 additions & 1 deletion crates/rspack_core/src/compiler/module_executor/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,6 @@ impl ModuleExecutor {
let dep = LoaderImportDependency::new(
request.clone(),
original_module_context.unwrap_or(Context::from("")),
original_module_identifier,
);
let dep_id = *dep.id();
v.insert(dep_id);
Expand Down
10 changes: 6 additions & 4 deletions crates/rspack_core/src/dependency/loader_import.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,21 @@
use super::AffectType;
use crate::{
AsContextDependency, AsDependencyTemplate, Context, Dependency, DependencyCategory, DependencyId,
DependencyType, ModuleDependency, ModuleIdentifier,
DependencyType, ModuleDependency,
};

#[derive(Debug, Hash, PartialEq, Eq, Clone)]
pub struct LoaderImportDependency {
id: DependencyId,
pub context: Context,
pub original_module: Option<ModuleIdentifier>,
request: String,
}

impl LoaderImportDependency {
pub fn new(request: String, context: Context, original_module: Option<ModuleIdentifier>) -> Self {
pub fn new(request: String, context: Context) -> Self {
Self {
request,
context,
original_module,
id: DependencyId::new(),
}
}
Expand All @@ -31,6 +29,10 @@ impl Dependency for LoaderImportDependency {
&self.id
}

fn get_context(&self) -> Option<&Context> {
Some(&self.context)
}

fn category(&self) -> &DependencyCategory {
&DependencyCategory::LoaderImport
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import(/* webpackChunkName: "chunk-b" */'./b');
export default "a";
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import(/* webpackChunkName: "chunk-c" */'./c');
export default "b";
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default "c";
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default 1
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import v from './imported-module'

import(/* webpackChunkName: "chunk-a" */'./a');

it("should inject mock runtime module", async function () {
expect(v).toBe(1)
expect(typeof __webpack_require__.mock).toBe("function");
expect(__webpack_require__.mock("chunk-a")).toBe("chunk-a.bundle0.js");
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const path = require('path')

module.exports = async function loader() {
const callback = this.async()
const result = await this.importModule(path.resolve(__dirname, './execute-module.js'))
callback(null, `export default ${result.default}`)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
const { RuntimeModule, RuntimeGlobals } = require("@rspack/core");

class MockRuntimeModule extends RuntimeModule {
constructor() {
super("mock");
}

generate(compilation) {
const chunkIdToName = this.chunk.getChunkMaps(false).name;
const chunkNameToId = Object.fromEntries(
Object.entries(chunkIdToName).map(([chunkId, chunkName]) => [
chunkName,
chunkId,
]),
);

return `
__webpack_require__.mock = function(chunkId) {
chunkId = (${JSON.stringify(
chunkNameToId,
)})[chunkId]||chunkId;
return ${RuntimeGlobals.publicPath} + ${RuntimeGlobals.getChunkScriptFilename}(chunkId);
};
`;
}
}

/** @type {import("@rspack/core").Configuration} */
module.exports = {
entry: "./index.js",
mode: "development",
devtool: false,
module: {
rules: [
{ test: /imported-module\.js/, use: ['./loader']}
]
},
optimization: {
minimize: false,
sideEffects: false,
concatenateModules: false,
usedExports: false,
innerGraph: false,
providedExports: false
},
plugins: [
compiler => {
compiler.hooks.thisCompilation.tap(
"MockRuntimePlugin",
(compilation) => {
compilation.hooks.runtimeRequirementInTree.tap("MockRuntimePlugin", (chunk, set) => {
set.add(RuntimeGlobals.publicPath);
set.add(RuntimeGlobals.getChunkScriptFilename);
compilation.addRuntimeModule(
chunk,
new MockRuntimeModule(chunk)
);
})
}
);
}
],
};
3 changes: 2 additions & 1 deletion packages/rspack/src/loader-runner/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -404,9 +404,10 @@ export async function runLoaders(
};
loaderContext.importModule = function importModule(
request,
options,
userOptions,
callback
) {
const options = userOptions ? userOptions : {};
if (!callback) {
return new Promise((resolve, reject) => {
compiler
Expand Down

0 comments on commit 5d0cba7

Please sign in to comment.