Skip to content

Commit

Permalink
feat: add entry filename supports
Browse files Browse the repository at this point in the history
  • Loading branch information
xusd320 committed Feb 6, 2025
1 parent 5378030 commit c4e1ff9
Show file tree
Hide file tree
Showing 14 changed files with 98 additions and 24 deletions.
2 changes: 1 addition & 1 deletion crates/mako/src/compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,7 @@ impl Compiler {
.entry
.values()
.map(|entry| {
let mut entry = entry.to_string_lossy().to_string();
let mut entry = entry.import.to_string_lossy().to_string();
let is_browser = matches!(
self.context.config.platform,
crate::config::Platform::Browser
Expand Down
29 changes: 19 additions & 10 deletions crates/mako/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ mod code_splitting;
mod dev_server;
mod devtool;
mod duplicate_package_checker;
pub mod entry;
mod experimental;
mod external;
mod generic_usize;
Expand All @@ -29,9 +30,9 @@ mod tree_shaking;
mod umd;
mod watch;

use std::collections::{BTreeMap, HashMap};
use std::collections::HashMap;
use std::fmt;
use std::path::{Path, PathBuf};
use std::path::Path;

pub use analyze::AnalyzeConfig;
use anyhow::{anyhow, Result};
Expand All @@ -43,6 +44,7 @@ pub use devtool::{deserialize_devtool, DevtoolConfig};
pub use duplicate_package_checker::{
deserialize_check_duplicate_package, DuplicatePackageCheckerConfig,
};
use entry::{Entry, EntryItem};
use experimental::ExperimentalConfig;
pub use external::{
ExternalAdvanced, ExternalAdvancedSubpath, ExternalAdvancedSubpathConverter,
Expand Down Expand Up @@ -130,7 +132,7 @@ pub enum Platform {
#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Config {
pub entry: BTreeMap<String, PathBuf>,
pub entry: Entry,
pub output: OutputConfig,
pub resolve: ResolveConfig,
#[serde(deserialize_with = "deserialize_manifest", default)]
Expand Down Expand Up @@ -365,7 +367,13 @@ impl Config {
for ext in JS_EXTENSIONS {
let file_path = root.join(file_path).with_extension(ext);
if file_path.exists() {
config.entry.insert("index".to_string(), file_path);
config.entry.insert(
"index".to_string(),
EntryItem {
filename: None,
import: file_path,
},
);
break 'outer;
}
}
Expand All @@ -378,28 +386,29 @@ impl Config {
// normalize entry
config.entry.iter_mut().try_for_each(|(k, v)| {
#[allow(clippy::needless_borrows_for_generic_args)]
if let Ok(entry_path) = root.join(&v).canonicalize()
if let Ok(entry_path) = root.join(&v.import).canonicalize()
&& entry_path.is_file()
{
*v = entry_path;
v.import = entry_path;
} else {
for ext in JS_EXTENSIONS {
#[allow(clippy::needless_borrows_for_generic_args)]
if let Ok(entry_path) = root.join(&v).with_extension(ext).canonicalize()
if let Ok(entry_path) =
root.join(&v.import).with_extension(ext).canonicalize()
&& entry_path.is_file()
{
*v = entry_path;
v.import = entry_path;
return Ok(());
}

if let Ok(entry_path) = root
.join(&v)
.join(&v.import)
.join("index")
.with_extension(ext)
.canonicalize()
&& entry_path.is_file()
{
*v = entry_path;
v.import = entry_path;
return Ok(());
}
}
Expand Down
37 changes: 37 additions & 0 deletions crates/mako/src/config/entry.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
use std::collections::BTreeMap;
use std::path::PathBuf;

use serde::{Deserialize, Serialize};
use serde_json::Value;

#[derive(Serialize, Debug)]
pub struct EntryItem {
#[serde(default)]
pub filename: Option<String>,
pub import: PathBuf,
}

pub type Entry = BTreeMap<String, EntryItem>;

impl<'de> Deserialize<'de> for EntryItem {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value: serde_json::Value = serde_json::Value::deserialize(deserializer)?;
match &value {
Value::String(s) => Ok(EntryItem {
filename: None,
import: s.into(),
}),
Value::Object(_) => {
Ok(serde_json::from_value::<EntryItem>(value).map_err(serde::de::Error::custom)?)
}
_ => Err(serde::de::Error::custom(format!(
"invalid `{}` value: {}",
stringify!(deserialize_umd).replace("deserialize_", ""),
value
))),
}
}
}
1 change: 1 addition & 0 deletions crates/mako/src/config/module_federation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use serde::{Deserialize, Serialize};
#[serde(rename_all = "camelCase")]
pub struct ModuleFederationConfig {
pub name: String,
pub filename: Option<String>,
pub exposes: Option<ExposesConfig>,
pub shared: Option<SharedConfig>,
pub remotes: Option<RemotesConfig>,
Expand Down
9 changes: 4 additions & 5 deletions crates/mako/src/config/umd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,12 @@ where
D: serde::Deserializer<'de>,
{
let value: serde_json::Value = serde_json::Value::deserialize(deserializer)?;
match value {
serde_json::Value::Object(obj) => Ok(Some(
serde_json::from_value::<Umd>(serde_json::Value::Object(obj))
.map_err(serde::de::Error::custom)?,
match &value {
serde_json::Value::Object(_) => Ok(Some(
serde_json::from_value::<Umd>(value).map_err(serde::de::Error::custom)?,
)),
serde_json::Value::String(name) => Ok(Some(Umd {
name,
name: name.clone(),
..Default::default()
})),
serde_json::Value::Bool(false) => Ok(None),
Expand Down
2 changes: 1 addition & 1 deletion crates/mako/src/dev/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ impl Compiler {
debug!("build by modify: {:?} start", entry);
// first build
let is_entry = {
let mut entries = self.context.config.entry.values();
let mut entries = self.context.config.entry.values().map(|e| &e.import);
entries.any(|e| e.eq(entry))
};

Expand Down
7 changes: 6 additions & 1 deletion crates/mako/src/generate/chunk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,12 @@ impl Chunk {
}

pub fn filename(&self) -> String {
format!("{}.js", self.name())
let name = self.name();
if name.ends_with(".js") {
name
} else {
format!("{}.js", self.name())
}
}

pub fn add_module(&mut self, module_id: ModuleId) {
Expand Down
11 changes: 10 additions & 1 deletion crates/mako/src/generate/chunk_pot/ast_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,11 @@ pub(crate) fn render_entry_js_chunk(
.into_bytes()
};

let entry_info = match &chunk.chunk_type {
ChunkType::Entry(_, name, _) => context.config.entry.get(name).unwrap(),
_ => panic!("normal chunk {} rendered as entry chunk", chunk.id.id),
};

Ok(ChunkFile {
raw_hash: hmr_hash,
content,
Expand All @@ -227,7 +232,11 @@ pub(crate) fn render_entry_js_chunk(
chunk_id: pot.chunk_id.clone(),
file_type: ChunkFileType::JS,
chunk_name: pot.chunk_name.clone(),
file_name_template: context.config.output.filename.clone(),
file_name_template: entry_info
.filename
.as_ref()
.xor(context.config.output.filename.as_ref())
.cloned(),
})
}

Expand Down
11 changes: 10 additions & 1 deletion crates/mako/src/generate/chunk_pot/str_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,11 @@ pub(super) fn render_entry_js_chunk(
let mut source_map_buf: Vec<u8> = vec![];
sourcemap::SourceMap::from(chunk_raw_sourcemap).to_writer(&mut source_map_buf)?;

let entry_info = match &chunk.chunk_type {
ChunkType::Entry(_, name, _) => context.config.entry.get(name).unwrap(),
_ => panic!("normal chunk {} rendered as entry chunk", chunk.id.id),
};

Ok(ChunkFile {
raw_hash: hmr_hash,
content,
Expand All @@ -103,7 +108,11 @@ pub(super) fn render_entry_js_chunk(
file_name: pot.js_name.clone(),
chunk_id: pot.chunk_id.clone(),
file_type: ChunkFileType::JS,
file_name_template: None,
file_name_template: entry_info
.filename
.as_ref()
.xor(context.config.output.filename.as_ref())
.cloned(),
chunk_name: pot.chunk_name.clone(),
})
}
Expand Down
2 changes: 1 addition & 1 deletion crates/mako/src/generate/group_chunk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ impl Compiler {

for (key, value) in &self.context.config.entry {
// hmr entry id has query '?hmr'
if parse_path(&value.to_string_lossy()).unwrap().0
if parse_path(&value.import.to_string_lossy()).unwrap().0
== parse_path(&entry.id).unwrap().0
{
entry_chunk_name = key;
Expand Down
6 changes: 5 additions & 1 deletion crates/mako/src/plugins/module_federation/container.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use tracing::warn;
use super::constants::{FEDERATION_EXPOSE_CHUNK_PREFIX, FEDERATION_GLOBAL};
use super::util::parse_remote;
use super::ModuleFederationPlugin;
use crate::config::entry::EntryItem;
use crate::config::{AllowChunks, Config};
use crate::module::md5_hash;
use crate::visitors::mako_require::MAKO_REQUIRE;
Expand Down Expand Up @@ -38,7 +39,10 @@ impl ModuleFederationPlugin {
}
fs::write(&container_entry_path, container_entry_code).unwrap();

vacant_entry.insert(container_entry_path);
vacant_entry.insert(EntryItem {
filename: self.config.filename.clone(),
import: container_entry_path,
});
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion crates/mako/src/plugins/ssu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ impl Plugin for SUPlus {

fn modify_config(&self, config: &mut Config, _root: &Path, _args: &Args) -> Result<()> {
for p in config.entry.values_mut() {
*p = PathBuf::from(format!("{SSU_ENTRY_PREFIX}{}", p.to_string_lossy()));
p.import = PathBuf::from(format!("{SSU_ENTRY_PREFIX}{}", p.import.to_string_lossy()));
}

config.code_splitting = Some(CodeSplitting {
Expand Down
2 changes: 1 addition & 1 deletion examples/module-federation/host/mako.config.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
"moduleFederation": {
"name": "mfHost",
"remotes": {
"widget": "mfWidget@http://localhost:3000/mfWidget.js"
"widget": "mfWidget@http://localhost:3000/remoteEntry.js"
},
"shared": { "react": { "eager": true }, "react-dom": { "eager": true } },
"implementation": "../../../../../packages/mako/node_modules/@module-federation/webpack-bundler-runtime"
Expand Down
1 change: 1 addition & 0 deletions examples/module-federation/widget/mako.config.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"publicPath": "auto",
"moduleFederation": {
"name": "mfWidget",
"filename": "remoteEntry.js",
"exposes": {
"./App1": "./src/App1.tsx",
"./App2": "./src/App2.tsx"
Expand Down

0 comments on commit c4e1ff9

Please sign in to comment.