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: move ensure runtime to entry #1660

Merged
merged 14 commits into from
Nov 13, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
1 change: 1 addition & 0 deletions crates/mako/src/compiler.rs
Copy link
Contributor

Choose a reason for hiding this comment

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

加个 e2e? 看下 entry 被改成什么样了

Original file line number Diff line number Diff line change
Expand Up @@ -248,6 +248,7 @@ impl Compiler {
Arc::new(plugins::runtime::MakoRuntime {}),
Arc::new(plugins::invalid_webpack_syntax::InvalidWebpackSyntaxPlugin {}),
Arc::new(plugins::hmr_runtime::HMRRuntimePlugin {}),
Arc::new(plugins::ensure_2::Ensure2 {}),
Arc::new(plugins::wasm_runtime::WasmRuntimePlugin {}),
Arc::new(plugins::async_runtime::AsyncRuntimePlugin {}),
Arc::new(plugins::emotion::EmotionPlugin {}),
Expand Down
1 change: 1 addition & 0 deletions crates/mako/src/plugins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ pub mod copy;
pub mod detect_circular_dependence;
pub mod duplicate_package_checker;
pub mod emotion;
pub mod ensure_2;
pub mod graphviz;
pub mod hmr_runtime;
pub mod ignore;
Expand Down
64 changes: 64 additions & 0 deletions crates/mako/src/plugins/ensure_2.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
use std::collections::BTreeMap;
use std::sync::Arc;

use crate::compiler::Context;
use crate::generate::chunk::ChunkType;
use crate::plugin::Plugin;

pub struct Ensure2 {}

impl Plugin for Ensure2 {
fn name(&self) -> &str {
"dev_ensure2"
}
fn runtime_plugins(&self, _context: &Arc<Context>) -> anyhow::Result<Vec<String>> {
let cg = _context.chunk_graph.read().unwrap();

let mut chunk_async_map: BTreeMap<String, Vec<String>> = BTreeMap::new();

cg.get_chunks()
.into_iter()
.filter(|chunk| chunk.chunk_type == ChunkType::Async)
.for_each(|chunk| {
let chunk_ids = {
[
cg.sync_dependencies_chunk(&chunk.id),
vec![chunk.id.clone()],
]
.concat()
.iter()
.filter_map(|chunk_id| {
// skip empty chunk because it will not be generated
if cg.chunk(chunk_id).is_some_and(|c| !c.modules.is_empty()) {
Some(chunk_id.id.clone())
} else {
None
}
})
.collect::<Vec<_>>()
};
chunk_async_map.insert(chunk.id.id.clone(), chunk_ids);
});
stormslowly marked this conversation as resolved.
Show resolved Hide resolved

// TODO: compress the map to reduce duplicated chunk ids
let ensure_map = serde_json::to_string(&chunk_async_map)?;

let runtime = format!(
r#"
(function(){{
let map = {ensure_map};
requireModule.ensure2 = function(chunkId){{
let toEnsure = map[chunkId];
if (toEnsure) {{
return Promise.all(toEnsure.map(function(c){{ return requireModule.ensure(c); }}))
}}else{{
return Promise.resolve();
}}
}};
}})();
"#
);

Ok(vec![runtime])
}
}
62 changes: 39 additions & 23 deletions crates/mako/src/visitors/dynamic_import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ use crate::ast::utils::{is_dynamic_import, promise_all, require_ensure};
use crate::ast::DUMMY_CTXT;
use crate::compiler::Context;
use crate::generate::chunk::ChunkId;
use crate::module::generate_module_id;
use crate::visitors::dep_replacer::DependenciesToReplace;

pub struct DynamicImport<'a> {
Expand Down Expand Up @@ -75,6 +74,7 @@ impl<'a> VisitMut for DynamicImport<'a> {
if call_expr.args.is_empty() {
return;
}

if let ExprOrSpread {
expr: box Expr::Lit(Lit::Str(ref mut source)),
..
Expand Down Expand Up @@ -106,8 +106,9 @@ impl<'a> VisitMut for DynamicImport<'a> {
// it must be resolved, so unwrap is safe here.
.unwrap();

let chunk_ids = {
let chunk_id: ChunkId = resolved_info.0.as_str().into();
let resolved_source = &resolved_info.0;
let _chunk_ids = {
let chunk_id: ChunkId = resolved_source.clone().into();
let chunk_graph = &self.context.chunk_graph.read().unwrap();
let chunk = chunk_graph.chunk(&chunk_id);
let chunk_ids = match chunk {
Expand Down Expand Up @@ -142,35 +143,23 @@ impl<'a> VisitMut for DynamicImport<'a> {
// e.g.
// Promise.all([ require.ensure("id") ]).then(require.bind(require, "id"))
// Promise.all([ require.ensure("d1"), require.ensure("id)]).then(require.bind(require, "id"))
*expr = {
let to_ensure_elems = chunk_ids
.iter()
.map(|c_id| {
Some(ExprOrSpread {
spread: None,
expr: Box::new(require_ensure(c_id.clone())),
})
})
.collect::<Vec<_>>();
let load_promise = promise_all(ExprOrSpread {
spread: None,
expr: ArrayLit {
span: DUMMY_SP,
elems: to_ensure_elems,
}
.into(),
});

let require_module = generate_module_id(&resolved_info.1, &self.context);
// version 2
// require.ensure2("id").then(require.bind(require,"id"))

*expr = {
// let load_promise = self.make_load_promise(&chunk_ids);
let load_promise = self.make_load_promise_2(resolved_source);

let lazy_require_call =
member_expr!(DUMMY_CTXT, DUMMY_SP, __mako_require__.bind).as_call(
DUMMY_SP,
vec![
quote_ident!("__mako_require__").as_arg(),
quote_str!(require_module.as_str()).as_arg(),
quote_str!(resolved_source.clone()).as_arg(),
],
);

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

优化新表达式的构建过程

在构建新的表达式时,可以考虑简化 lazy_require_calldr_call 的生成逻辑,避免重复代码,从而提高代码效率。

let dr_call = member_expr!(DUMMY_CTXT, DUMMY_SP, __mako_require__.dr)
.as_call(
DUMMY_SP,
Expand All @@ -187,6 +176,33 @@ impl<'a> VisitMut for DynamicImport<'a> {
}
}

impl DynamicImport<'_> {
fn make_load_promise_2(&self, module_id: &str) -> Expr {
member_expr!(DUMMY_CTXT, DUMMY_SP, __mako_require__.ensure2)
.as_call(DUMMY_SP, vec![quote_str!(module_id).as_arg()])
}

fn make_load_promise(&self, chunk_ids: &[String]) -> Expr {
let to_ensure_elems = chunk_ids
.iter()
.map(|c_id| {
Some(ExprOrSpread {
spread: None,
expr: Box::new(require_ensure(c_id.clone())),
})
})
.collect::<Vec<_>>();
promise_all(ExprOrSpread {
spread: None,
expr: ArrayLit {
span: DUMMY_SP,
elems: to_ensure_elems,
}
.into(),
})
}
}

#[cfg(test)]
mod tests {
use std::collections::HashMap;
Expand Down
Loading