Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/master' into fix/skip_modules_ig…
Browse files Browse the repository at this point in the history
…nore_default_import
  • Loading branch information
stormslowly committed Jan 17, 2024
2 parents c0b7318 + 513828e commit e9078a3
Show file tree
Hide file tree
Showing 64 changed files with 1,906 additions and 428 deletions.
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,12 @@
## 0.3.1

`2024-01-11`

> @alipay/bigfish@4.1.15
* 修复产物中模块 ID 的注释被 glob 表达式意外切断导致运行报错的问题 by [@PeachScript](https://github.com/PeachScript) in [#856](https://github.com/umijs/mako/pull/856)
* 优化内置插件钩子及暴露的 js hooks by [@sorrycc](https://github.com/sorrycc) in [#855](https://github.com/umijs/mako/pull/855)

## 0.2.3

`2024-01-10`
Expand All @@ -13,6 +22,10 @@
> @alipay/bigfish@4.1.14
* 修复 import/export 语句中使用 `as` 对同一导出使用多次导致的变量 undefined 问题 by [@stormslowly](https://github.com/stormslowly) in [#850](https://github.com/umijs/mako/pull/850)
* 修复 dev 启动时缺少的依赖在补齐后仍然构建失败的问题 by [@zhangpanweb](https://github.com/zhangpanweb) in [#845](https://github.com/umijs/mako/pull/845)
* 修复 less 文件中引入相对路径的 css 可能解析失败的问题 by [@sorrycc](https://github.com/sorrycc) in [#844](https://github.com/umijs/mako/pull/844)
* 优化产物生成,在不压缩时保留注释便于开发者排查问题 by [@sorrycc](https://github.com/sorrycc) in [#848](https://github.com/umijs/mako/pull/848)
* 优化产物生成,为模块声明添加 ID 注释便于开发者排查问题 by [@sorrycc](https://github.com/sorrycc) in [#849](https://github.com/umijs/mako/pull/849)

## 0.2.1

Expand Down
82 changes: 76 additions & 6 deletions Cargo.lock

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

1 change: 1 addition & 0 deletions crates/mako/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ serde = { workspace = true }
serde_json = { workspace = true }
cached = { workspace = true }
swc_core = { workspace = true, features = ["swc_ecma_quote_macros"] }
miette = { version = "5.10.0", features = ["fancy"] }

[dev-dependencies]
insta = { version = "1.30.0", features = ["yaml"] }
Expand Down
45 changes: 45 additions & 0 deletions crates/mako/src/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ impl Compiler {
pub fn build(&self) -> Result<()> {
debug!("build");
let t_build = Instant::now();
self.context.plugin_driver.build_start(&self.context)?;
let entries: Vec<&PathBuf> = self.context.config.entry.values().collect();
let tasks = entries
.iter()
Expand Down Expand Up @@ -209,6 +210,34 @@ impl Compiler {
});
}

pub fn create_module_from_error(
err: String,
task: &Task,
context: &Arc<Context>,
) -> Result<Module> {
let module_id = ModuleId::new(task.path.clone());
let code = format!("throw new Error(`Module build failed:\n{:}`)", err);
let ast = build_js_ast(&task.path, code.as_str(), context)?;
let info = ModuleInfo {
ast: ModuleAst::Script(ast),
path: task.path.clone(),
external: None,
raw: "".to_string(),
raw_hash: 0,
missing_deps: Default::default(),
ignored_deps: vec![],
top_level_await: false,
is_async: false,
resolved_resource: task.parent_resource.clone(),
source_map_chain: vec![],
import_map: vec![],
export_map: vec![],
is_barrel: false,
};
let module = Module::new(module_id, task.is_entry, Some(info));
Ok(module)
}

pub fn create_module(
resource: &ResolverResource,
dep_module_id: &ModuleId,
Expand Down Expand Up @@ -269,6 +298,22 @@ module.exports = new Promise((resolve, reject) => {{
pub fn build_module(
context: &Arc<Context>,
task: task::Task,
) -> Result<(Module, ModuleDeps, Task)> {
let result = Compiler::build_module_inner(context, task.clone());
if let Err(err) = &result {
if context.args.watch {
let module =
Self::create_module_from_error(err.to_string(), &task, context).unwrap();
eprintln!("{}", err);
return Ok((module, vec![], task));
}
}
result
}

pub fn build_module_inner(
context: &Arc<Context>,
task: task::Task,
) -> Result<(Module, ModuleDeps, Task)> {
// load
let content = load(&task, context)?;
Expand Down
10 changes: 9 additions & 1 deletion crates/mako/src/chunk_pot/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,8 @@ pub(crate) fn pot_to_module_object(pot: &ChunkPot, context: &Arc<Context>) -> Re
let span = Span::dummy_with_cmt();
let id = module.0.id.id.clone();
let id = relative_to_root(id, &context.root);
// to avoid comment broken by glob=**/* for context module
let id = id.replace("*/", "*\\/");
comments.add_leading(
span.hi,
Comment {
Expand Down Expand Up @@ -266,7 +268,13 @@ fn to_module_fn_expr(module: &Module) -> Result<FnExpr> {

for n in script.ast.body.iter() {
match n.as_stmt() {
None => return Err(anyhow!("Error: {:?} not a stmt in ", module.id.id)),
None => {
return Err(anyhow!(
"Error: not a stmt found in {:?}, ast: {:?}",
module.id.id,
n,
));
}
Some(stmt) => {
stmts.push(stmt.clone());
}
Expand Down
34 changes: 24 additions & 10 deletions crates/mako/src/compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use std::collections::HashMap;
use std::fs;
use std::path::PathBuf;
use std::sync::{Arc, Mutex, RwLock};
use std::time::Instant;
use std::time::{Instant, UNIX_EPOCH};

use mako_core::anyhow::{anyhow, Error, Result};
use mako_core::colored::Colorize;
Expand All @@ -16,7 +16,7 @@ use crate::comments::Comments;
use crate::config::{hash_config, Config, OutputMode};
use crate::module_graph::ModuleGraph;
use crate::optimize_chunk::OptimizeChunksInfo;
use crate::plugin::{Plugin, PluginDriver};
use crate::plugin::{Plugin, PluginDriver, PluginGenerateEndParams, PluginGenerateStats};
use crate::plugins;
use crate::plugins::minifish::Inject;
use crate::resolve::{get_resolvers, Resolvers};
Expand Down Expand Up @@ -103,7 +103,6 @@ impl Context {

pub fn get_static_content<T: AsRef<str>>(&self, path: T) -> Option<Vec<u8>> {
let map = self.static_cache.read().unwrap();

map.read(path)
}
}
Expand Down Expand Up @@ -220,7 +219,9 @@ impl Compiler {
args: Args,
extra_plugins: Option<Vec<Arc<dyn Plugin>>>,
) -> Result<Self> {
assert!(root.is_absolute(), "root path must be absolute");
if !root.is_absolute() {
return Err(anyhow!("root path must be absolute"));
}

// why add plugins before builtin plugins?
// because plugins like less-loader need to be added before assets plugin
Expand Down Expand Up @@ -357,10 +358,11 @@ impl Compiler {
pub fn compile(&self) -> Result<()> {
// 先清空 dist 目录
if self.context.config.clean {
self.clean_dist();
self.clean_dist()?;
}

let t_compiler = Instant::now();
let start_time = std::time::SystemTime::now();
let is_prod = self.context.config.mode == crate::config::Mode::Production;
let building_with_message = format!(
"Building with {} for {}...",
Expand All @@ -377,19 +379,31 @@ impl Compiler {
mako_core::mako_profile_scope!("Generate Stage");
self.generate()
};
let t_compiler = t_compiler.elapsed();
let t_compiler_duration = t_compiler.elapsed();
if result.is_ok() {
println!(
"{}",
format!(
"✓ Built in {}",
format!("{}ms", t_compiler.as_millis()).bold()
format!("{}ms", t_compiler_duration.as_millis()).bold()
)
.green()
);
if !self.context.args.watch {
println!("{}", "Complete!".bold());
}
let end_time = std::time::SystemTime::now();
let params = PluginGenerateEndParams {
is_first_compile: true,
time: t_compiler.elapsed().as_millis() as u64,
stats: PluginGenerateStats {
start_time: start_time.duration_since(UNIX_EPOCH)?.as_millis() as u64,
end_time: end_time.duration_since(UNIX_EPOCH)?.as_millis() as u64,
},
};
self.context
.plugin_driver
.generate_end(&params, &self.context)?;
Ok(())
} else {
result
Expand All @@ -400,15 +414,15 @@ impl Compiler {
mako_core::mako_profile_function!();
let cg = self.context.chunk_graph.read().unwrap();
let mg = self.context.module_graph.read().unwrap();

cg.full_hash(&mg)
}

pub fn clean_dist(&self) {
pub fn clean_dist(&self) -> Result<()> {
// compiler 前清除 dist,如果后续 dev 环境不在 output_path 里,需要再补上 dev 的逻辑
let output_path = &self.context.config.output.path;
if fs::metadata(output_path).is_ok() {
fs::remove_dir_all(output_path).unwrap();
fs::remove_dir_all(output_path)?;
}
Ok(())
}
}
Loading

0 comments on commit e9078a3

Please sign in to comment.