From c05fb461b87caa8d799e1c18a7a32477adcd85ef Mon Sep 17 00:00:00 2001 From: Jinbao1001 Date: Mon, 23 Sep 2024 10:48:05 +0800 Subject: [PATCH 1/9] Revert "revert: import namespace optimize (#1606)" This reverts commit a48535838a28a1668ce2f5c309b4c1416b70986a. --- .github/workflows/ci.yml | 2 + crates/mako/src/plugins/tree_shaking.rs | 1 + .../tree_shaking/collect_explicit_prop.rs | 222 ++++++++++++++++++ .../tree_shaking/remove_useless_stmts.rs | 79 ++++++- crates/mako/src/plugins/tree_shaking/shake.rs | 20 +- .../tree-shaking.import_namespace/expect.js | 14 ++ .../mako.config.json | 5 + .../src/index.tsx | 21 ++ .../tree-shaking.import_namespace/src/mod.js | 11 + 9 files changed, 363 insertions(+), 12 deletions(-) create mode 100644 crates/mako/src/plugins/tree_shaking/collect_explicit_prop.rs create mode 100644 e2e/fixtures/tree-shaking.import_namespace/expect.js create mode 100644 e2e/fixtures/tree-shaking.import_namespace/mako.config.json create mode 100644 e2e/fixtures/tree-shaking.import_namespace/src/index.tsx create mode 100644 e2e/fixtures/tree-shaking.import_namespace/src/mod.js diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c941f67ba..05bec3386 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -115,6 +115,8 @@ jobs: - name: LS run: ls -l ./packages/mako - name: Test E2E + env: + RUST_BACKTRACE: full run: pnpm ${{ matrix.script }} lint: diff --git a/crates/mako/src/plugins/tree_shaking.rs b/crates/mako/src/plugins/tree_shaking.rs index be12f6306..b425e8de6 100644 --- a/crates/mako/src/plugins/tree_shaking.rs +++ b/crates/mako/src/plugins/tree_shaking.rs @@ -9,6 +9,7 @@ use crate::compiler::Context; use crate::module_graph::ModuleGraph; use crate::plugin::{Plugin, PluginTransformJsParam}; +mod collect_explicit_prop; mod module; mod module_side_effects_flag; mod remove_useless_stmts; diff --git a/crates/mako/src/plugins/tree_shaking/collect_explicit_prop.rs b/crates/mako/src/plugins/tree_shaking/collect_explicit_prop.rs new file mode 100644 index 000000000..9f1ca985a --- /dev/null +++ b/crates/mako/src/plugins/tree_shaking/collect_explicit_prop.rs @@ -0,0 +1,222 @@ +use std::collections::{HashMap, HashSet}; + +use swc_core::ecma::ast::{ComputedPropName, Id, Ident, Lit, MemberExpr, MemberProp}; +use swc_core::ecma::visit::{Visit, VisitWith}; + +#[derive(Debug)] +pub struct IdExplicitPropAccessCollector { + to_detected: HashSet, + accessed_by_explicit_prop_count: HashMap, + ident_accessed_count: HashMap, + accessed_by: HashMap>, +} + +impl IdExplicitPropAccessCollector { + pub(crate) fn new(ids: HashSet) -> Self { + Self { + to_detected: ids, + accessed_by_explicit_prop_count: Default::default(), + ident_accessed_count: Default::default(), + accessed_by: Default::default(), + } + } + pub(crate) fn explicit_accessed_props(mut self) -> HashMap> { + self.to_detected + .iter() + .filter_map(|id| { + let member_prop_accessed = self.accessed_by_explicit_prop_count.get(id); + let ident_accessed = self.ident_accessed_count.get(id); + + match (member_prop_accessed, ident_accessed) { + // all ident are accessed explicitly, so there is member expr there is a name + // ident, and at last plus the extra ident in import decl, that's 1 comes from. + (Some(m), Some(i)) if (i - m) == 1 => { + let mut accessed_by = Vec::from_iter(self.accessed_by.remove(id).unwrap()); + accessed_by.sort(); + + let str_key = format!("{}#{}", id.0, id.1.as_u32()); + + Some((str_key, accessed_by)) + } + // Some un-explicitly access e.g: obj[foo] + _ => None, + } + }) + .collect() + } + + fn increase_explicit_prop_accessed_count(&mut self, id: Id) { + self.accessed_by_explicit_prop_count + .entry(id.clone()) + .and_modify(|c| { + *c += 1; + }) + .or_insert(1); + } + + fn insert_member_accessed_by(&mut self, id: Id, prop: &str) { + self.increase_explicit_prop_accessed_count(id.clone()); + self.accessed_by + .entry(id) + .and_modify(|accessed| { + accessed.insert(prop.to_string()); + }) + .or_insert(HashSet::from([prop.to_string()])); + } +} + +impl Visit for IdExplicitPropAccessCollector { + fn visit_ident(&mut self, n: &Ident) { + let id = n.to_id(); + + if self.to_detected.contains(&id) { + self.ident_accessed_count + .entry(id) + .and_modify(|c| { + *c += 1; + }) + .or_insert(1); + } + } + + fn visit_member_expr(&mut self, n: &MemberExpr) { + if let Some(obj_ident) = n.obj.as_ident() { + let id = obj_ident.to_id(); + + if self.to_detected.contains(&id) { + match &n.prop { + MemberProp::Ident(prop_ident) => { + self.insert_member_accessed_by(id, prop_ident.sym.as_ref()); + } + MemberProp::PrivateName(_) => {} + MemberProp::Computed(ComputedPropName { expr, .. }) => { + if let Some(lit) = expr.as_lit() + && let Lit::Str(str) = lit + { + let visited_by = str.value.to_string(); + self.insert_member_accessed_by(id, &visited_by) + } + } + } + } + } + + n.visit_children_with(self); + } +} + +#[cfg(test)] +mod tests { + use maplit::hashset; + + use super::*; + use crate::ast::tests::TestUtils; + + #[test] + fn test_no_prop() { + let fields = extract_explicit_fields( + r#" + import * as foo from "./foo.js"; + console.log(foo) + "#, + ); + + assert_eq!(fields, None); + } + #[test] + fn test_no_access() { + let fields = extract_explicit_fields( + r#" + import * as foo from "./foo.js"; + "#, + ); + + assert_eq!(fields, None); + } + + #[test] + fn test_computed_prop() { + let fields = extract_explicit_fields( + r#" + import * as foo from "./foo.js"; + foo['f' + 'o' + 'o'] + "#, + ); + + assert_eq!(fields, None); + } + + #[test] + fn test_simple_explicit_prop() { + let fields = extract_explicit_fields( + r#" + import * as foo from "./foo.js"; + foo.x; + foo.y; + "#, + ); + + assert_eq!(fields.unwrap(), vec!["x".to_string(), "y".to_string()]); + } + + #[test] + fn test_nest_prop_explicit_prop() { + let fields = extract_explicit_fields( + r#" + import * as foo from "./foo.js"; + foo.x.z[foo.y] + "#, + ); + + assert_eq!(fields.unwrap(), vec!["x".to_string(), "y".to_string()]); + } + + #[test] + fn test_string_literal_prop_explicit() { + let fields = extract_explicit_fields( + r#" + import * as foo from "./foo.js"; + foo['x'] + "#, + ); + + assert_eq!(fields.unwrap(), vec!["x".to_string()]); + } + + #[test] + fn test_num_literal_prop_not_explicit() { + let fields = extract_explicit_fields( + r#" + import * as foo from "./foo.js"; + foo[1] + "#, + ); + + assert_eq!(fields, None); + } + + fn extract_explicit_fields(code: &str) -> Option> { + let tu = TestUtils::gen_js_ast(code); + + let id = namespace_id(&tu); + let str = format!("{}#{}", id.0, id.1.as_u32()); + + let mut v = IdExplicitPropAccessCollector::new(hashset! { id }); + tu.ast.js().ast.visit_with(&mut v); + + v.explicit_accessed_props().remove(&str) + } + + fn namespace_id(tu: &TestUtils) -> Id { + tu.ast.js().ast.body[0] + .as_module_decl() + .unwrap() + .as_import() + .unwrap() + .specifiers[0] + .as_namespace() + .unwrap() + .local + .to_id() + } +} diff --git a/crates/mako/src/plugins/tree_shaking/remove_useless_stmts.rs b/crates/mako/src/plugins/tree_shaking/remove_useless_stmts.rs index ac7da5850..dde449438 100644 --- a/crates/mako/src/plugins/tree_shaking/remove_useless_stmts.rs +++ b/crates/mako/src/plugins/tree_shaking/remove_useless_stmts.rs @@ -1,9 +1,16 @@ +use std::collections::HashSet; + +use swc_core::common::util::take::Take; +use swc_core::common::SyntaxContext; use swc_core::ecma::ast::{ - Decl, ExportDecl, ExportSpecifier, ImportDecl, ImportSpecifier, Module as SwcModule, - ModuleExportName, + Decl, ExportDecl, ExportSpecifier, Id, ImportDecl, ImportSpecifier, Module as SwcModule, + Module, ModuleExportName, }; +use swc_core::ecma::transforms::compat::es2015::destructuring; +use swc_core::ecma::transforms::compat::es2018::object_rest_spread; use swc_core::ecma::visit::{VisitMut, VisitMutWith, VisitWith}; +use super::collect_explicit_prop::IdExplicitPropAccessCollector; use crate::plugins::tree_shaking::module::TreeShakeModule; use crate::plugins::tree_shaking::statement_graph::analyze_imports_and_exports::{ analyze_imports_and_exports, StatementInfo, @@ -105,10 +112,10 @@ pub fn remove_useless_stmts( // remove from the end to the start stmts_to_remove.reverse(); - for stmt in stmts_to_remove { swc_module.body.remove(stmt); } + optimize_import_namespace(&mut used_import_infos, swc_module); (used_import_infos, used_export_from_infos) } @@ -231,6 +238,72 @@ impl VisitMut for UselessExportStmtRemover { } } +fn optimize_import_namespace(import_infos: &mut [ImportInfo], module: &mut Module) { + let namespaces = import_infos + .iter() + .filter_map(|import_info| { + let ns = import_info + .specifiers + .iter() + .filter_map(|sp| match sp { + ImportSpecifierInfo::Namespace(ns) => Some(ns.clone()), + _ => None, + }) + .collect::>(); + if ns.is_empty() { + None + } else { + Some(ns) + } + }) + .flatten() + .collect::>(); + + let ids = namespaces + .iter() + .map(|ns| { + let (sym, ctxt) = ns.rsplit_once('#').unwrap(); + (sym.into(), SyntaxContext::from_u32(ctxt.parse().unwrap())) + }) + .collect::>(); + + if !ids.is_empty() { + let mut v = IdExplicitPropAccessCollector::new(ids); + let mut shadow = module.clone(); + + shadow.visit_mut_with(&mut object_rest_spread(Default::default())); + shadow.visit_mut_with(&mut destructuring(Default::default())); + shadow.visit_with(&mut v); + + let explicit_prop_accessed_ids = v.explicit_accessed_props(); + + import_infos.iter_mut().for_each(|ii| { + ii.specifiers = ii + .specifiers + .take() + .into_iter() + .flat_map(|specifier_info| { + if let ImportSpecifierInfo::Namespace(ref ns) = specifier_info { + if let Some(visited_fields) = explicit_prop_accessed_ids.get(ns) { + return visited_fields + .iter() + .map(|v| { + let imported_name = format!("{v}#0"); + ImportSpecifierInfo::Named { + imported: Some(imported_name.clone()), + local: imported_name, + } + }) + .collect::>(); + } + } + vec![specifier_info] + }) + .collect::>(); + }) + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/mako/src/plugins/tree_shaking/shake.rs b/crates/mako/src/plugins/tree_shaking/shake.rs index 05b8916b1..4f236f4ae 100644 --- a/crates/mako/src/plugins/tree_shaking/shake.rs +++ b/crates/mako/src/plugins/tree_shaking/shake.rs @@ -11,6 +11,7 @@ use anyhow::Result; use rayon::prelude::*; use swc_core::common::util::take::Take; use swc_core::common::GLOBALS; +use swc_core::ecma::transforms::base::helpers::{Helpers, HELPERS}; use self::skip_module::skip_module_optimize; use crate::compiler::Context; @@ -134,7 +135,7 @@ pub fn optimize_modules(module_graph: &mut ModuleGraph, context: &Arc) let mut current_index: usize = 0; let len = tree_shake_modules_ids.len(); - { + GLOBALS.set(&context.meta.script.globals, || { mako_profile_scope!("tree-shake"); while current_index < len { @@ -142,15 +143,16 @@ pub fn optimize_modules(module_graph: &mut ModuleGraph, context: &Arc) "tree-shake-module", &tree_shake_modules_ids[current_index].id ); - - current_index = shake_module( - module_graph, - &tree_shake_modules_ids, - &tree_shake_modules_map, - current_index, - ); + HELPERS.set(&Helpers::new(true), || { + current_index = shake_module( + module_graph, + &tree_shake_modules_ids, + &tree_shake_modules_map, + current_index, + ); + }); } - } + }); { mako_profile_scope!("update ast"); diff --git a/e2e/fixtures/tree-shaking.import_namespace/expect.js b/e2e/fixtures/tree-shaking.import_namespace/expect.js new file mode 100644 index 000000000..ed279bea0 --- /dev/null +++ b/e2e/fixtures/tree-shaking.import_namespace/expect.js @@ -0,0 +1,14 @@ +const assert = require("assert"); +const { + parseBuildResult, + injectSimpleJest, + moduleReg, +} = require("../../../scripts/test-utils"); +const { files } = parseBuildResult(__dirname); + +injectSimpleJest(); +const content = files["index.js"]; + +expect(content).toContain("shouldKeep1"); +expect(content).toContain("shouldKeep2"); +expect(content).not.toContain("shouldNotKeep"); diff --git a/e2e/fixtures/tree-shaking.import_namespace/mako.config.json b/e2e/fixtures/tree-shaking.import_namespace/mako.config.json new file mode 100644 index 000000000..5c422f400 --- /dev/null +++ b/e2e/fixtures/tree-shaking.import_namespace/mako.config.json @@ -0,0 +1,5 @@ +{ + "optimization": { + "concatenateModules": false + } +} diff --git a/e2e/fixtures/tree-shaking.import_namespace/src/index.tsx b/e2e/fixtures/tree-shaking.import_namespace/src/index.tsx new file mode 100644 index 000000000..cfba35f0a --- /dev/null +++ b/e2e/fixtures/tree-shaking.import_namespace/src/index.tsx @@ -0,0 +1,21 @@ +import * as mod from "./mod"; + +const { shouldKeep2 } = mod + +console.log(mod.shouldKeep1(42)); +console.log(shouldKeep2(42)) + +// Guardian don't remove +let array= [1,2,3,] +console.log(array) +let [first, ...rest] = array +console.log(first,rest) +let copiedArray = [...array] +console.log(copiedArray) + +let object = {a: 1,b: 2,c: 3} +console.log(object) +let {a, ...restObject} = object +console.log(a,restObject) +let copiedObject = {...object} +console.log(copiedObject) diff --git a/e2e/fixtures/tree-shaking.import_namespace/src/mod.js b/e2e/fixtures/tree-shaking.import_namespace/src/mod.js new file mode 100644 index 000000000..5882ccb73 --- /dev/null +++ b/e2e/fixtures/tree-shaking.import_namespace/src/mod.js @@ -0,0 +1,11 @@ +export function shouldKeep1(x) { + return x * x; +} + +export function shouldKeep2(x) { + return x + x; +} + +export function shouldNotKeep(x) { + return x * x * x; +} From 198dff830e692c99b56e7d6cc8703c2b9ce5e1c6 Mon Sep 17 00:00:00 2001 From: Jinbao1001 Date: Tue, 24 Sep 2024 17:52:41 +0800 Subject: [PATCH 2/9] fix: hash not stable --- crates/mako/src/module_graph.rs | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/crates/mako/src/module_graph.rs b/crates/mako/src/module_graph.rs index 550f2d983..9c8548fcf 100644 --- a/crates/mako/src/module_graph.rs +++ b/crates/mako/src/module_graph.rs @@ -314,18 +314,19 @@ impl ModuleGraph { while let Some((edge_index, _node_index)) = edges.next(&self.graph) { let dependencies = self.graph.edge_weight_mut(edge_index).unwrap(); - - if let Some(to_del_dep) = dependencies - .iter() - .position(|dep| *source == dep.source && dep.resolve_type.same_enum(&resolve_type)) - { - dependencies.take(&dependencies.iter().nth(to_del_dep).unwrap().clone()); - - if dependencies.is_empty() { - self.graph.remove_edge(edge_index); + let mut found = false; + dependencies.retain(|dep| { + if !found && source == &dep.source && dep.resolve_type.same_enum(&resolve_type) { + found = true; + false + } else { + true } - return; + }); + if dependencies.is_empty() { + self.graph.remove_edge(edge_index); } + return; } } From bea938cd9086bb7d99e4ac3dbe9ea98d127650ef Mon Sep 17 00:00:00 2001 From: Jinbao1001 Date: Tue, 24 Sep 2024 21:04:30 +0800 Subject: [PATCH 3/9] fix: deps sort not stable --- crates/mako/src/module_graph.rs | 10 ++++++++ .../plugins/tree_shaking/shake/skip_module.rs | 23 +++++++++---------- 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/crates/mako/src/module_graph.rs b/crates/mako/src/module_graph.rs index 9c8548fcf..b714dbd55 100644 --- a/crates/mako/src/module_graph.rs +++ b/crates/mako/src/module_graph.rs @@ -330,6 +330,16 @@ impl ModuleGraph { } } + pub fn rewrite_dependency(&mut self, module_id: &ModuleId, deps: Vec<(&ModuleId, Dependency)>) { + let mut edges = self.get_edges(module_id, Direction::Outgoing); + while let Some((edge_index, _node_index)) = edges.next(&self.graph) { + self.graph.remove_edge(edge_index); + } + deps.iter().for_each(|(m, d)| { + self.add_dependency(module_id, m, d.clone()); + }); + } + pub fn get_dependency_module_by_source( &self, module_id: &ModuleId, diff --git a/crates/mako/src/plugins/tree_shaking/shake/skip_module.rs b/crates/mako/src/plugins/tree_shaking/shake/skip_module.rs index 6589cb092..1eed7835b 100644 --- a/crates/mako/src/plugins/tree_shaking/shake/skip_module.rs +++ b/crates/mako/src/plugins/tree_shaking/shake/skip_module.rs @@ -11,6 +11,7 @@ use swc_core::ecma::ast::{ use swc_core::ecma::utils::{quote_ident, quote_str}; use swc_core::quote; +use crate::build::analyze_deps; use crate::compiler::Context; use crate::module::{Dependency, ImportType, ModuleId, NamedExportType, ResolveType}; use crate::module_graph::ModuleGraph; @@ -181,10 +182,11 @@ pub(super) fn skip_module_optimize( to_replace: &(StatementId, Vec, String), module_id: &ModuleId, module_graph: &mut ModuleGraph, + context: &Arc, ) { let stmt_id = to_replace.0; let replaces = &to_replace.1; - let source = &to_replace.2; + let _source = &to_replace.2; let module = module_graph.get_module_mut(module_id).unwrap(); @@ -330,16 +332,13 @@ pub(super) fn skip_module_optimize( swc_module.body.splice(stmt_id..stmt_id, to_insert); } - if to_delete { - module_graph.remove_dependency_module_by_source_and_resolve_type( - module_id, - source, - resolve_type.unwrap(), - ); - } - for dep in to_insert_deps { - module_graph.add_dependency(module_id, &dep.source.clone().into(), dep); - } + let info = &module.info.as_mut().unwrap(); + let mut deps_vec: Vec<(&ModuleId, Dependency)> = vec![]; + let deps = analyze_deps::AnalyzeDeps::analyze_deps(&info.ast, &info.file, context.clone()); + deps.unwrap().resolved_deps.iter().for_each(|r| { + deps_vec.push((&module_id, r.dependency.clone())); + }); + module_graph.rewrite_dependency(module_id, deps_vec); } while current_index < len { @@ -496,7 +495,7 @@ pub(super) fn skip_module_optimize( // stmt_id is reversed order for to_replace in replaces.iter() { // println!("{} apply with {:?}", module_id.id, to_replace.1); - apply_replace(to_replace, module_id, module_graph); + apply_replace(to_replace, module_id, module_graph, _context); } let mut tsm = tree_shake_modules_map.get(module_id).unwrap().borrow_mut(); From 19bfccd61c3f9d0ae57454392999e64a2bfc375b Mon Sep 17 00:00:00 2001 From: Jinbao1001 Date: Tue, 24 Sep 2024 21:07:21 +0800 Subject: [PATCH 4/9] fix: deps sort not stable --- crates/mako/src/module_graph.rs | 28 +------------------ .../plugins/tree_shaking/shake/skip_module.rs | 5 ---- 2 files changed, 1 insertion(+), 32 deletions(-) diff --git a/crates/mako/src/module_graph.rs b/crates/mako/src/module_graph.rs index b714dbd55..b881bbac3 100644 --- a/crates/mako/src/module_graph.rs +++ b/crates/mako/src/module_graph.rs @@ -9,7 +9,7 @@ use petgraph::visit::IntoEdgeReferences; use petgraph::Direction; use tracing::{debug, warn}; -use crate::module::{Dependencies, Dependency, Module, ModuleId, ResolveType}; +use crate::module::{Dependencies, Dependency, Module, ModuleId}; #[derive(Debug)] pub struct ModuleGraph { @@ -304,32 +304,6 @@ impl ModuleGraph { targets } - pub fn remove_dependency_module_by_source_and_resolve_type( - &mut self, - module_id: &ModuleId, - source: &String, - resolve_type: ResolveType, - ) { - let mut edges = self.get_edges(module_id, Direction::Outgoing); - - while let Some((edge_index, _node_index)) = edges.next(&self.graph) { - let dependencies = self.graph.edge_weight_mut(edge_index).unwrap(); - let mut found = false; - dependencies.retain(|dep| { - if !found && source == &dep.source && dep.resolve_type.same_enum(&resolve_type) { - found = true; - false - } else { - true - } - }); - if dependencies.is_empty() { - self.graph.remove_edge(edge_index); - } - return; - } - } - pub fn rewrite_dependency(&mut self, module_id: &ModuleId, deps: Vec<(&ModuleId, Dependency)>) { let mut edges = self.get_edges(module_id, Direction::Outgoing); while let Some((edge_index, _node_index)) = edges.next(&self.graph) { diff --git a/crates/mako/src/plugins/tree_shaking/shake/skip_module.rs b/crates/mako/src/plugins/tree_shaking/shake/skip_module.rs index 1eed7835b..4b451c6cb 100644 --- a/crates/mako/src/plugins/tree_shaking/shake/skip_module.rs +++ b/crates/mako/src/plugins/tree_shaking/shake/skip_module.rs @@ -196,13 +196,10 @@ pub(super) fn skip_module_optimize( let mut to_insert = vec![]; let mut to_insert_deps = vec![]; let mut to_delete = false; - let mut resolve_type: Option = None; match &mut stmt { ModuleItem::ModuleDecl(module_decl) => match module_decl { ModuleDecl::Import(import_decl) => { - resolve_type = Some(ResolveType::Import(ImportType::empty())); - for replace in replaces { let mut matched_index = None; let mut matched_ident = None; @@ -254,8 +251,6 @@ pub(super) fn skip_module_optimize( ModuleDecl::ExportDecl(_) => {} ModuleDecl::ExportNamed(export_named) => { if export_named.src.is_some() { - resolve_type = Some(ResolveType::ExportNamed(NamedExportType::empty())); - for replace in replaces { let mut matched_index = None; let mut matched_ident = None; From e01bcc3e4afcf3a33b09bf7b8bb539570fe4a3a7 Mon Sep 17 00:00:00 2001 From: Jinbao1001 Date: Tue, 24 Sep 2024 23:10:17 +0800 Subject: [PATCH 5/9] fix: deps sort not stable --- crates/mako/src/module_graph.rs | 2 +- .../plugins/tree_shaking/shake/skip_module.rs | 7 +- packages/mako/src/binding.d.ts | 226 +++++++++++++ packages/mako/src/binding.js | 309 ++++++++++++++++++ 4 files changed, 541 insertions(+), 3 deletions(-) create mode 100644 packages/mako/src/binding.d.ts create mode 100644 packages/mako/src/binding.js diff --git a/crates/mako/src/module_graph.rs b/crates/mako/src/module_graph.rs index b881bbac3..feb9256b4 100644 --- a/crates/mako/src/module_graph.rs +++ b/crates/mako/src/module_graph.rs @@ -304,7 +304,7 @@ impl ModuleGraph { targets } - pub fn rewrite_dependency(&mut self, module_id: &ModuleId, deps: Vec<(&ModuleId, Dependency)>) { + pub fn rewrite_dependency(&mut self, module_id: &ModuleId, deps: Vec<(ModuleId, Dependency)>) { let mut edges = self.get_edges(module_id, Direction::Outgoing); while let Some((edge_index, _node_index)) = edges.next(&self.graph) { self.graph.remove_edge(edge_index); diff --git a/crates/mako/src/plugins/tree_shaking/shake/skip_module.rs b/crates/mako/src/plugins/tree_shaking/shake/skip_module.rs index 4b451c6cb..67b5f1fb7 100644 --- a/crates/mako/src/plugins/tree_shaking/shake/skip_module.rs +++ b/crates/mako/src/plugins/tree_shaking/shake/skip_module.rs @@ -328,10 +328,13 @@ pub(super) fn skip_module_optimize( } let info = &module.info.as_mut().unwrap(); - let mut deps_vec: Vec<(&ModuleId, Dependency)> = vec![]; + let mut deps_vec: Vec<(ModuleId, Dependency)> = vec![]; let deps = analyze_deps::AnalyzeDeps::analyze_deps(&info.ast, &info.file, context.clone()); deps.unwrap().resolved_deps.iter().for_each(|r| { - deps_vec.push((&module_id, r.dependency.clone())); + deps_vec.push(( + ModuleId::new(r.resolver_resource.get_resolved_path()), + r.dependency.clone(), + )); }); module_graph.rewrite_dependency(module_id, deps_vec); } diff --git a/packages/mako/src/binding.d.ts b/packages/mako/src/binding.d.ts new file mode 100644 index 000000000..a9989c8a2 --- /dev/null +++ b/packages/mako/src/binding.d.ts @@ -0,0 +1,226 @@ +/* tslint:disable */ +/* eslint-disable */ + +/* auto-generated by NAPI-RS */ + +export interface JsHooks { + name?: string; + load?: ( + filePath: string, + ) => Promise<{ content: string; type: 'css' | 'js' } | void> | void; + generateEnd?: (data: { + isFirstCompile: boolean; + time: number; + stats: { + hash: number; + builtAt: number; + rootPath: string; + outputPath: string; + assets: { type: string; name: string; path: string; size: number }[]; + chunkModules: { + type: string; + id: string; + chunks: string[]; + size: number; + }[]; + modules: Record< + string, + { id: string; dependents: string[]; dependencies: string[] } + >; + chunks: { + type: string; + id: string; + files: string[]; + entry: boolean; + modules: { type: string; id: string; size: number; chunks: string[] }[]; + siblings: string[]; + origin: { + module: string; + moduleIdentifier: string; + moduleName: string; + loc: string; + request: string; + }[]; + }[]; + entrypoints: Record; + rscClientComponents: { path; string; moduleId: string }[]; + rscCSSModules: { path; string; moduleId: string; modules: boolean }[]; + startTime: number; + endTime: number; + }; + }) => void; + onGenerateFile?: (path: string, content: Buffer) => Promise; + buildStart?: () => Promise; +} +export interface BuildParams { + root: string; + config: { + entry?: Record; + output?: { + path: string; + mode: 'bundle' | 'bundless'; + esVersion?: string; + meta?: boolean; + preserveModules?: boolean; + preserveModulesRoot?: string; + skipWrite?: boolean; + }; + resolve?: { + alias?: Array<[string, string]>; + extensions?: string[]; + }; + manifest?: + | false + | { + fileName: string; + basePath: string; + }; + mode?: 'development' | 'production'; + define?: Record; + devtool?: false | 'source-map' | 'inline-source-map'; + externals?: Record< + string, + | string + | { + root: string; + script?: string; + subpath?: { + exclude?: string[]; + rules: { + regex: string; + target: string | '$EMPTY'; + targetConverter?: 'PascalCase'; + }[]; + }; + } + >; + copy?: string[]; + codeSplitting?: + | false + | { + strategy: 'auto'; + } + | { + strategy: 'granular'; + options: { + frameworkPackages: string[]; + libMinSize?: number; + }; + } + | { + strategy: 'advanced'; + options: { + minSize?: number; + groups: { + name: string; + allowChunks?: 'all' | 'entry' | 'async'; + test?: string; + minChunks?: number; + minSize?: number; + maxSize?: number; + priority?: number; + }[]; + }; + }; + providers?: Record; + publicPath?: string; + inlineLimit?: number; + targets?: Record; + platform?: 'node' | 'browser'; + hmr?: false | {}; + devServer?: false | { host?: string; port?: number }; + px2rem?: + | false + | { + root?: number; + propBlackList?: string[]; + propWhiteList?: string[]; + selectorBlackList?: string[]; + selectorWhiteList?: string[]; + selectorDoubleList?: string[]; + mediaQuery?: boolean; + }; + stats?: boolean; + hash?: boolean; + autoCSSModules?: boolean; + ignoreCSSParserErrors?: boolean; + dynamicImportToRequire?: boolean; + umd?: false | string; + cjs?: boolean; + writeToDisk?: boolean; + transformImport?: { + libraryName: string; + libraryDirectory?: string; + style?: boolean | string; + }[]; + clean?: boolean; + nodePolyfill?: boolean; + ignores?: string[]; + moduleIdStrategy?: 'hashed' | 'named'; + minify?: boolean; + _minifish?: + | false + | { + mapping: Record; + metaPath?: string; + inject?: Record< + string, + | { + from: string; + exclude?: string; + include?: string; + preferRequire?: boolean; + } + | { + from: string; + named: string; + exclude?: string; + include?: string; + preferRequire?: boolean; + } + | { + from: string; + namespace: true; + exclude?: string; + include?: string; + preferRequire?: boolean; + } + >; + }; + optimization?: + | false + | { + skipModules?: boolean; + }; + react?: { + runtime?: 'automatic' | 'classic'; + pragma?: string; + importSource?: string; + pragmaFrag?: string; + }; + emitAssets?: boolean; + cssModulesExportOnlyLocales?: boolean; + inlineCSS?: false | {}; + rscServer?: + | false + | { + emitCSS: boolean; + clientComponentTpl: string; + }; + rscClient?: + | false + | { + logServerComponent: 'error' | 'ignore'; + }; + experimental?: { + webpackSyntaxValidate?: string[]; + }; + watch?: { + ignoredPaths?: string[]; + _nodeModulesRegexes?: string[]; + }; + }; + plugins: Array; + watch: boolean; +} +export function build(buildParams: BuildParams): Promise; diff --git a/packages/mako/src/binding.js b/packages/mako/src/binding.js new file mode 100644 index 000000000..0561424b2 --- /dev/null +++ b/packages/mako/src/binding.js @@ -0,0 +1,309 @@ +/* tslint:disable */ +/* eslint-disable */ +/* prettier-ignore */ + +/* auto-generated by NAPI-RS */ + +const { existsSync, readFileSync } = require('fs'); +const { join } = require('path'); + +const { platform, arch } = process; + +let nativeBinding = null; +let localFileExisted = false; +let loadError = null; + +function isMusl() { + // For Node 10 + if (!process.report || typeof process.report.getReport !== 'function') { + try { + const lddPath = require('child_process') + .execSync('which ldd') + .toString() + .trim(); + return readFileSync(lddPath, 'utf8').includes('musl'); + } catch (e) { + return true; + } + } else { + const { glibcVersionRuntime } = process.report.getReport().header; + return !glibcVersionRuntime; + } +} + +switch (platform) { + case 'android': + switch (arch) { + case 'arm64': + localFileExisted = existsSync( + join(__dirname, 'mako.android-arm64.node'), + ); + try { + if (localFileExisted) { + nativeBinding = require('./mako.android-arm64.node'); + } else { + nativeBinding = require('@umijs/mako-android-arm64'); + } + } catch (e) { + loadError = e; + } + break; + case 'arm': + localFileExisted = existsSync( + join(__dirname, 'mako.android-arm-eabi.node'), + ); + try { + if (localFileExisted) { + nativeBinding = require('./mako.android-arm-eabi.node'); + } else { + nativeBinding = require('@umijs/mako-android-arm-eabi'); + } + } catch (e) { + loadError = e; + } + break; + default: + throw new Error(`Unsupported architecture on Android ${arch}`); + } + break; + case 'win32': + switch (arch) { + case 'x64': + localFileExisted = existsSync( + join(__dirname, 'mako.win32-x64-msvc.node'), + ); + try { + if (localFileExisted) { + nativeBinding = require('./mako.win32-x64-msvc.node'); + } else { + nativeBinding = require('@umijs/mako-win32-x64-msvc'); + } + } catch (e) { + loadError = e; + } + break; + case 'ia32': + localFileExisted = existsSync( + join(__dirname, 'mako.win32-ia32-msvc.node'), + ); + try { + if (localFileExisted) { + nativeBinding = require('./mako.win32-ia32-msvc.node'); + } else { + nativeBinding = require('@umijs/mako-win32-ia32-msvc'); + } + } catch (e) { + loadError = e; + } + break; + case 'arm64': + localFileExisted = existsSync( + join(__dirname, 'mako.win32-arm64-msvc.node'), + ); + try { + if (localFileExisted) { + nativeBinding = require('./mako.win32-arm64-msvc.node'); + } else { + nativeBinding = require('@umijs/mako-win32-arm64-msvc'); + } + } catch (e) { + loadError = e; + } + break; + default: + throw new Error(`Unsupported architecture on Windows: ${arch}`); + } + break; + case 'darwin': + localFileExisted = existsSync( + join(__dirname, 'mako.darwin-universal.node'), + ); + try { + if (localFileExisted) { + nativeBinding = require('./mako.darwin-universal.node'); + } else { + nativeBinding = require('@umijs/mako-darwin-universal'); + } + break; + } catch {} + switch (arch) { + case 'x64': + localFileExisted = existsSync(join(__dirname, 'mako.darwin-x64.node')); + try { + if (localFileExisted) { + nativeBinding = require('./mako.darwin-x64.node'); + } else { + nativeBinding = require('@umijs/mako-darwin-x64'); + } + } catch (e) { + loadError = e; + } + break; + case 'arm64': + localFileExisted = existsSync( + join(__dirname, 'mako.darwin-arm64.node'), + ); + try { + if (localFileExisted) { + nativeBinding = require('./mako.darwin-arm64.node'); + } else { + nativeBinding = require('@umijs/mako-darwin-arm64'); + } + } catch (e) { + loadError = e; + } + break; + default: + throw new Error(`Unsupported architecture on macOS: ${arch}`); + } + break; + case 'freebsd': + if (arch !== 'x64') { + throw new Error(`Unsupported architecture on FreeBSD: ${arch}`); + } + localFileExisted = existsSync(join(__dirname, 'mako.freebsd-x64.node')); + try { + if (localFileExisted) { + nativeBinding = require('./mako.freebsd-x64.node'); + } else { + nativeBinding = require('@umijs/mako-freebsd-x64'); + } + } catch (e) { + loadError = e; + } + break; + case 'linux': + switch (arch) { + case 'x64': + if (isMusl()) { + localFileExisted = existsSync( + join(__dirname, 'mako.linux-x64-musl.node'), + ); + try { + if (localFileExisted) { + nativeBinding = require('./mako.linux-x64-musl.node'); + } else { + nativeBinding = require('@umijs/mako-linux-x64-musl'); + } + } catch (e) { + loadError = e; + } + } else { + localFileExisted = existsSync( + join(__dirname, 'mako.linux-x64-gnu.node'), + ); + try { + if (localFileExisted) { + nativeBinding = require('./mako.linux-x64-gnu.node'); + } else { + nativeBinding = require('@umijs/mako-linux-x64-gnu'); + } + } catch (e) { + loadError = e; + } + } + break; + case 'arm64': + if (isMusl()) { + localFileExisted = existsSync( + join(__dirname, 'mako.linux-arm64-musl.node'), + ); + try { + if (localFileExisted) { + nativeBinding = require('./mako.linux-arm64-musl.node'); + } else { + nativeBinding = require('@umijs/mako-linux-arm64-musl'); + } + } catch (e) { + loadError = e; + } + } else { + localFileExisted = existsSync( + join(__dirname, 'mako.linux-arm64-gnu.node'), + ); + try { + if (localFileExisted) { + nativeBinding = require('./mako.linux-arm64-gnu.node'); + } else { + nativeBinding = require('@umijs/mako-linux-arm64-gnu'); + } + } catch (e) { + loadError = e; + } + } + break; + case 'arm': + localFileExisted = existsSync( + join(__dirname, 'mako.linux-arm-gnueabihf.node'), + ); + try { + if (localFileExisted) { + nativeBinding = require('./mako.linux-arm-gnueabihf.node'); + } else { + nativeBinding = require('@umijs/mako-linux-arm-gnueabihf'); + } + } catch (e) { + loadError = e; + } + break; + case 'riscv64': + if (isMusl()) { + localFileExisted = existsSync( + join(__dirname, 'mako.linux-riscv64-musl.node'), + ); + try { + if (localFileExisted) { + nativeBinding = require('./mako.linux-riscv64-musl.node'); + } else { + nativeBinding = require('@umijs/mako-linux-riscv64-musl'); + } + } catch (e) { + loadError = e; + } + } else { + localFileExisted = existsSync( + join(__dirname, 'mako.linux-riscv64-gnu.node'), + ); + try { + if (localFileExisted) { + nativeBinding = require('./mako.linux-riscv64-gnu.node'); + } else { + nativeBinding = require('@umijs/mako-linux-riscv64-gnu'); + } + } catch (e) { + loadError = e; + } + } + break; + case 's390x': + localFileExisted = existsSync( + join(__dirname, 'mako.linux-s390x-gnu.node'), + ); + try { + if (localFileExisted) { + nativeBinding = require('./mako.linux-s390x-gnu.node'); + } else { + nativeBinding = require('@umijs/mako-linux-s390x-gnu'); + } + } catch (e) { + loadError = e; + } + break; + default: + throw new Error(`Unsupported architecture on Linux: ${arch}`); + } + break; + default: + throw new Error(`Unsupported OS: ${platform}, architecture: ${arch}`); +} + +if (!nativeBinding) { + if (loadError) { + throw loadError; + } + throw new Error(`Failed to load native binding`); +} + +const { build } = nativeBinding; + +module.exports.build = build; From b4335d1ca536c58ddd57bdf125b1af952f6475bc Mon Sep 17 00:00:00 2001 From: Jinbao1001 Date: Tue, 24 Sep 2024 23:12:07 +0800 Subject: [PATCH 6/9] fix: delete binding --- packages/mako/binding.d.ts | 226 --------------------------- packages/mako/binding.js | 309 ------------------------------------- 2 files changed, 535 deletions(-) delete mode 100644 packages/mako/binding.d.ts delete mode 100644 packages/mako/binding.js diff --git a/packages/mako/binding.d.ts b/packages/mako/binding.d.ts deleted file mode 100644 index a9989c8a2..000000000 --- a/packages/mako/binding.d.ts +++ /dev/null @@ -1,226 +0,0 @@ -/* tslint:disable */ -/* eslint-disable */ - -/* auto-generated by NAPI-RS */ - -export interface JsHooks { - name?: string; - load?: ( - filePath: string, - ) => Promise<{ content: string; type: 'css' | 'js' } | void> | void; - generateEnd?: (data: { - isFirstCompile: boolean; - time: number; - stats: { - hash: number; - builtAt: number; - rootPath: string; - outputPath: string; - assets: { type: string; name: string; path: string; size: number }[]; - chunkModules: { - type: string; - id: string; - chunks: string[]; - size: number; - }[]; - modules: Record< - string, - { id: string; dependents: string[]; dependencies: string[] } - >; - chunks: { - type: string; - id: string; - files: string[]; - entry: boolean; - modules: { type: string; id: string; size: number; chunks: string[] }[]; - siblings: string[]; - origin: { - module: string; - moduleIdentifier: string; - moduleName: string; - loc: string; - request: string; - }[]; - }[]; - entrypoints: Record; - rscClientComponents: { path; string; moduleId: string }[]; - rscCSSModules: { path; string; moduleId: string; modules: boolean }[]; - startTime: number; - endTime: number; - }; - }) => void; - onGenerateFile?: (path: string, content: Buffer) => Promise; - buildStart?: () => Promise; -} -export interface BuildParams { - root: string; - config: { - entry?: Record; - output?: { - path: string; - mode: 'bundle' | 'bundless'; - esVersion?: string; - meta?: boolean; - preserveModules?: boolean; - preserveModulesRoot?: string; - skipWrite?: boolean; - }; - resolve?: { - alias?: Array<[string, string]>; - extensions?: string[]; - }; - manifest?: - | false - | { - fileName: string; - basePath: string; - }; - mode?: 'development' | 'production'; - define?: Record; - devtool?: false | 'source-map' | 'inline-source-map'; - externals?: Record< - string, - | string - | { - root: string; - script?: string; - subpath?: { - exclude?: string[]; - rules: { - regex: string; - target: string | '$EMPTY'; - targetConverter?: 'PascalCase'; - }[]; - }; - } - >; - copy?: string[]; - codeSplitting?: - | false - | { - strategy: 'auto'; - } - | { - strategy: 'granular'; - options: { - frameworkPackages: string[]; - libMinSize?: number; - }; - } - | { - strategy: 'advanced'; - options: { - minSize?: number; - groups: { - name: string; - allowChunks?: 'all' | 'entry' | 'async'; - test?: string; - minChunks?: number; - minSize?: number; - maxSize?: number; - priority?: number; - }[]; - }; - }; - providers?: Record; - publicPath?: string; - inlineLimit?: number; - targets?: Record; - platform?: 'node' | 'browser'; - hmr?: false | {}; - devServer?: false | { host?: string; port?: number }; - px2rem?: - | false - | { - root?: number; - propBlackList?: string[]; - propWhiteList?: string[]; - selectorBlackList?: string[]; - selectorWhiteList?: string[]; - selectorDoubleList?: string[]; - mediaQuery?: boolean; - }; - stats?: boolean; - hash?: boolean; - autoCSSModules?: boolean; - ignoreCSSParserErrors?: boolean; - dynamicImportToRequire?: boolean; - umd?: false | string; - cjs?: boolean; - writeToDisk?: boolean; - transformImport?: { - libraryName: string; - libraryDirectory?: string; - style?: boolean | string; - }[]; - clean?: boolean; - nodePolyfill?: boolean; - ignores?: string[]; - moduleIdStrategy?: 'hashed' | 'named'; - minify?: boolean; - _minifish?: - | false - | { - mapping: Record; - metaPath?: string; - inject?: Record< - string, - | { - from: string; - exclude?: string; - include?: string; - preferRequire?: boolean; - } - | { - from: string; - named: string; - exclude?: string; - include?: string; - preferRequire?: boolean; - } - | { - from: string; - namespace: true; - exclude?: string; - include?: string; - preferRequire?: boolean; - } - >; - }; - optimization?: - | false - | { - skipModules?: boolean; - }; - react?: { - runtime?: 'automatic' | 'classic'; - pragma?: string; - importSource?: string; - pragmaFrag?: string; - }; - emitAssets?: boolean; - cssModulesExportOnlyLocales?: boolean; - inlineCSS?: false | {}; - rscServer?: - | false - | { - emitCSS: boolean; - clientComponentTpl: string; - }; - rscClient?: - | false - | { - logServerComponent: 'error' | 'ignore'; - }; - experimental?: { - webpackSyntaxValidate?: string[]; - }; - watch?: { - ignoredPaths?: string[]; - _nodeModulesRegexes?: string[]; - }; - }; - plugins: Array; - watch: boolean; -} -export function build(buildParams: BuildParams): Promise; diff --git a/packages/mako/binding.js b/packages/mako/binding.js deleted file mode 100644 index 0561424b2..000000000 --- a/packages/mako/binding.js +++ /dev/null @@ -1,309 +0,0 @@ -/* tslint:disable */ -/* eslint-disable */ -/* prettier-ignore */ - -/* auto-generated by NAPI-RS */ - -const { existsSync, readFileSync } = require('fs'); -const { join } = require('path'); - -const { platform, arch } = process; - -let nativeBinding = null; -let localFileExisted = false; -let loadError = null; - -function isMusl() { - // For Node 10 - if (!process.report || typeof process.report.getReport !== 'function') { - try { - const lddPath = require('child_process') - .execSync('which ldd') - .toString() - .trim(); - return readFileSync(lddPath, 'utf8').includes('musl'); - } catch (e) { - return true; - } - } else { - const { glibcVersionRuntime } = process.report.getReport().header; - return !glibcVersionRuntime; - } -} - -switch (platform) { - case 'android': - switch (arch) { - case 'arm64': - localFileExisted = existsSync( - join(__dirname, 'mako.android-arm64.node'), - ); - try { - if (localFileExisted) { - nativeBinding = require('./mako.android-arm64.node'); - } else { - nativeBinding = require('@umijs/mako-android-arm64'); - } - } catch (e) { - loadError = e; - } - break; - case 'arm': - localFileExisted = existsSync( - join(__dirname, 'mako.android-arm-eabi.node'), - ); - try { - if (localFileExisted) { - nativeBinding = require('./mako.android-arm-eabi.node'); - } else { - nativeBinding = require('@umijs/mako-android-arm-eabi'); - } - } catch (e) { - loadError = e; - } - break; - default: - throw new Error(`Unsupported architecture on Android ${arch}`); - } - break; - case 'win32': - switch (arch) { - case 'x64': - localFileExisted = existsSync( - join(__dirname, 'mako.win32-x64-msvc.node'), - ); - try { - if (localFileExisted) { - nativeBinding = require('./mako.win32-x64-msvc.node'); - } else { - nativeBinding = require('@umijs/mako-win32-x64-msvc'); - } - } catch (e) { - loadError = e; - } - break; - case 'ia32': - localFileExisted = existsSync( - join(__dirname, 'mako.win32-ia32-msvc.node'), - ); - try { - if (localFileExisted) { - nativeBinding = require('./mako.win32-ia32-msvc.node'); - } else { - nativeBinding = require('@umijs/mako-win32-ia32-msvc'); - } - } catch (e) { - loadError = e; - } - break; - case 'arm64': - localFileExisted = existsSync( - join(__dirname, 'mako.win32-arm64-msvc.node'), - ); - try { - if (localFileExisted) { - nativeBinding = require('./mako.win32-arm64-msvc.node'); - } else { - nativeBinding = require('@umijs/mako-win32-arm64-msvc'); - } - } catch (e) { - loadError = e; - } - break; - default: - throw new Error(`Unsupported architecture on Windows: ${arch}`); - } - break; - case 'darwin': - localFileExisted = existsSync( - join(__dirname, 'mako.darwin-universal.node'), - ); - try { - if (localFileExisted) { - nativeBinding = require('./mako.darwin-universal.node'); - } else { - nativeBinding = require('@umijs/mako-darwin-universal'); - } - break; - } catch {} - switch (arch) { - case 'x64': - localFileExisted = existsSync(join(__dirname, 'mako.darwin-x64.node')); - try { - if (localFileExisted) { - nativeBinding = require('./mako.darwin-x64.node'); - } else { - nativeBinding = require('@umijs/mako-darwin-x64'); - } - } catch (e) { - loadError = e; - } - break; - case 'arm64': - localFileExisted = existsSync( - join(__dirname, 'mako.darwin-arm64.node'), - ); - try { - if (localFileExisted) { - nativeBinding = require('./mako.darwin-arm64.node'); - } else { - nativeBinding = require('@umijs/mako-darwin-arm64'); - } - } catch (e) { - loadError = e; - } - break; - default: - throw new Error(`Unsupported architecture on macOS: ${arch}`); - } - break; - case 'freebsd': - if (arch !== 'x64') { - throw new Error(`Unsupported architecture on FreeBSD: ${arch}`); - } - localFileExisted = existsSync(join(__dirname, 'mako.freebsd-x64.node')); - try { - if (localFileExisted) { - nativeBinding = require('./mako.freebsd-x64.node'); - } else { - nativeBinding = require('@umijs/mako-freebsd-x64'); - } - } catch (e) { - loadError = e; - } - break; - case 'linux': - switch (arch) { - case 'x64': - if (isMusl()) { - localFileExisted = existsSync( - join(__dirname, 'mako.linux-x64-musl.node'), - ); - try { - if (localFileExisted) { - nativeBinding = require('./mako.linux-x64-musl.node'); - } else { - nativeBinding = require('@umijs/mako-linux-x64-musl'); - } - } catch (e) { - loadError = e; - } - } else { - localFileExisted = existsSync( - join(__dirname, 'mako.linux-x64-gnu.node'), - ); - try { - if (localFileExisted) { - nativeBinding = require('./mako.linux-x64-gnu.node'); - } else { - nativeBinding = require('@umijs/mako-linux-x64-gnu'); - } - } catch (e) { - loadError = e; - } - } - break; - case 'arm64': - if (isMusl()) { - localFileExisted = existsSync( - join(__dirname, 'mako.linux-arm64-musl.node'), - ); - try { - if (localFileExisted) { - nativeBinding = require('./mako.linux-arm64-musl.node'); - } else { - nativeBinding = require('@umijs/mako-linux-arm64-musl'); - } - } catch (e) { - loadError = e; - } - } else { - localFileExisted = existsSync( - join(__dirname, 'mako.linux-arm64-gnu.node'), - ); - try { - if (localFileExisted) { - nativeBinding = require('./mako.linux-arm64-gnu.node'); - } else { - nativeBinding = require('@umijs/mako-linux-arm64-gnu'); - } - } catch (e) { - loadError = e; - } - } - break; - case 'arm': - localFileExisted = existsSync( - join(__dirname, 'mako.linux-arm-gnueabihf.node'), - ); - try { - if (localFileExisted) { - nativeBinding = require('./mako.linux-arm-gnueabihf.node'); - } else { - nativeBinding = require('@umijs/mako-linux-arm-gnueabihf'); - } - } catch (e) { - loadError = e; - } - break; - case 'riscv64': - if (isMusl()) { - localFileExisted = existsSync( - join(__dirname, 'mako.linux-riscv64-musl.node'), - ); - try { - if (localFileExisted) { - nativeBinding = require('./mako.linux-riscv64-musl.node'); - } else { - nativeBinding = require('@umijs/mako-linux-riscv64-musl'); - } - } catch (e) { - loadError = e; - } - } else { - localFileExisted = existsSync( - join(__dirname, 'mako.linux-riscv64-gnu.node'), - ); - try { - if (localFileExisted) { - nativeBinding = require('./mako.linux-riscv64-gnu.node'); - } else { - nativeBinding = require('@umijs/mako-linux-riscv64-gnu'); - } - } catch (e) { - loadError = e; - } - } - break; - case 's390x': - localFileExisted = existsSync( - join(__dirname, 'mako.linux-s390x-gnu.node'), - ); - try { - if (localFileExisted) { - nativeBinding = require('./mako.linux-s390x-gnu.node'); - } else { - nativeBinding = require('@umijs/mako-linux-s390x-gnu'); - } - } catch (e) { - loadError = e; - } - break; - default: - throw new Error(`Unsupported architecture on Linux: ${arch}`); - } - break; - default: - throw new Error(`Unsupported OS: ${platform}, architecture: ${arch}`); -} - -if (!nativeBinding) { - if (loadError) { - throw loadError; - } - throw new Error(`Failed to load native binding`); -} - -const { build } = nativeBinding; - -module.exports.build = build; From c0b9e5e98791e9aa9ad2524a097264a0f87a1c32 Mon Sep 17 00:00:00 2001 From: Jinbao1001 Date: Wed, 25 Sep 2024 13:28:28 +0800 Subject: [PATCH 7/9] fix: var name --- crates/mako/src/plugins/tree_shaking/shake/skip_module.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/mako/src/plugins/tree_shaking/shake/skip_module.rs b/crates/mako/src/plugins/tree_shaking/shake/skip_module.rs index 67b5f1fb7..06aa96b86 100644 --- a/crates/mako/src/plugins/tree_shaking/shake/skip_module.rs +++ b/crates/mako/src/plugins/tree_shaking/shake/skip_module.rs @@ -166,7 +166,7 @@ pub(super) fn skip_module_optimize( module_graph: &mut ModuleGraph, tree_shake_modules_ids: &Vec, tree_shake_modules_map: &HashMap>, - _context: &Arc, + context: &Arc, ) -> Result<()> { mako_profile_function!(); @@ -493,7 +493,7 @@ pub(super) fn skip_module_optimize( // stmt_id is reversed order for to_replace in replaces.iter() { // println!("{} apply with {:?}", module_id.id, to_replace.1); - apply_replace(to_replace, module_id, module_graph, _context); + apply_replace(to_replace, module_id, module_graph, context); } let mut tsm = tree_shake_modules_map.get(module_id).unwrap().borrow_mut(); From 1993386d768571215fc6c25257f67850d535db58 Mon Sep 17 00:00:00 2001 From: Jinbao1001 Date: Wed, 25 Sep 2024 13:59:45 +0800 Subject: [PATCH 8/9] chore: iter to into --- crates/mako/src/module_graph.rs | 4 ++-- crates/mako/src/plugins/tree_shaking/shake/skip_module.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/mako/src/module_graph.rs b/crates/mako/src/module_graph.rs index feb9256b4..cdff39630 100644 --- a/crates/mako/src/module_graph.rs +++ b/crates/mako/src/module_graph.rs @@ -309,8 +309,8 @@ impl ModuleGraph { while let Some((edge_index, _node_index)) = edges.next(&self.graph) { self.graph.remove_edge(edge_index); } - deps.iter().for_each(|(m, d)| { - self.add_dependency(module_id, m, d.clone()); + deps.into_iter().for_each(|(m, d)| { + self.add_dependency(module_id, &m, d); }); } diff --git a/crates/mako/src/plugins/tree_shaking/shake/skip_module.rs b/crates/mako/src/plugins/tree_shaking/shake/skip_module.rs index 06aa96b86..48ff402ba 100644 --- a/crates/mako/src/plugins/tree_shaking/shake/skip_module.rs +++ b/crates/mako/src/plugins/tree_shaking/shake/skip_module.rs @@ -330,10 +330,10 @@ pub(super) fn skip_module_optimize( let info = &module.info.as_mut().unwrap(); let mut deps_vec: Vec<(ModuleId, Dependency)> = vec![]; let deps = analyze_deps::AnalyzeDeps::analyze_deps(&info.ast, &info.file, context.clone()); - deps.unwrap().resolved_deps.iter().for_each(|r| { + deps.unwrap().resolved_deps.into_iter().for_each(|r| { deps_vec.push(( ModuleId::new(r.resolver_resource.get_resolved_path()), - r.dependency.clone(), + r.dependency, )); }); module_graph.rewrite_dependency(module_id, deps_vec); From 7447872b4ce5ddfcfde05842b48827a474627052 Mon Sep 17 00:00:00 2001 From: Jinbao1001 Date: Sat, 12 Oct 2024 16:12:02 +0800 Subject: [PATCH 9/9] fix: format --- crates/mako/src/plugins/tree_shaking/shake/skip_module.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/mako/src/plugins/tree_shaking/shake/skip_module.rs b/crates/mako/src/plugins/tree_shaking/shake/skip_module.rs index c1a65151e..94f2d76ac 100644 --- a/crates/mako/src/plugins/tree_shaking/shake/skip_module.rs +++ b/crates/mako/src/plugins/tree_shaking/shake/skip_module.rs @@ -11,8 +11,8 @@ use swc_core::ecma::ast::{ use swc_core::ecma::utils::{quote_ident, quote_str}; use swc_core::quote; -use crate::build::analyze_deps; use crate::ast::DUMMY_CTXT; +use crate::build::analyze_deps; use crate::compiler::Context; use crate::module::{Dependency, ImportType, ModuleId, NamedExportType, ResolveType}; use crate::module_graph::ModuleGraph;