Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
17 changes: 9 additions & 8 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 @@ -102,6 +102,7 @@ puffin_egui = { version = "0.22.0", optional = true }
rayon = "1.7.0"
regex = "1.9.3"
sailfish = "0.8.3"
semver = "1.0.23"
serde-xml-rs = "0.6.0"
serde_yaml = "0.9.22"
svgr-rs = "0.1.3"
Expand Down
9 changes: 9 additions & 0 deletions crates/mako/src/compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,15 @@ impl Compiler {
)));
}

if let Some(duplicate_package_checker) = &config.check_duplicate_package {
plugins.push(Arc::new(
plugins::duplicate_package_checker::DuplicatePackageCheckerPlugin::new()
.show_help(duplicate_package_checker.show_help)
.emit_error(duplicate_package_checker.emit_error)
.verbose(duplicate_package_checker.verbose),
));
}

if config.experimental.require_context {
plugins.push(Arc::new(plugins::require_context::RequireContextPlugin {}))
}
Expand Down
25 changes: 25 additions & 0 deletions crates/mako/src/config/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,10 @@ create_deserialize_fn!(deserialize_manifest, ManifestConfig);
create_deserialize_fn!(deserialize_code_splitting, CodeSplitting);
create_deserialize_fn!(deserialize_px2rem, Px2RemConfig);
create_deserialize_fn!(deserialize_progress, ProgressConfig);
create_deserialize_fn!(
deserialize_check_duplicate_package,
DuplicatePackageCheckerConfig
);
create_deserialize_fn!(deserialize_umd, String);
create_deserialize_fn!(deserialize_devtool, DevtoolConfig);
create_deserialize_fn!(deserialize_tree_shaking, TreeShakingStrategy);
Expand Down Expand Up @@ -281,6 +285,16 @@ pub struct ProgressConfig {
pub progress_chars: String,
}

#[derive(Deserialize, Serialize, Clone, Debug)]
pub struct DuplicatePackageCheckerConfig {
#[serde(rename = "verbose", default)]
pub verbose: bool,
#[serde(rename = "emitError", default)]
pub emit_error: bool,
#[serde(rename = "showHelp", default)]
pub show_help: bool,
}

impl Default for Px2RemConfig {
fn default() -> Self {
Px2RemConfig {
Expand Down Expand Up @@ -580,6 +594,12 @@ pub struct Config {
pub watch: WatchConfig,
pub use_define_for_class_fields: bool,
pub emit_decorator_metadata: bool,
#[serde(
rename = "duplicatePackageChecker",
deserialize_with = "deserialize_check_duplicate_package",
default
)]
pub check_duplicate_package: Option<DuplicatePackageCheckerConfig>,
}

#[derive(Deserialize, Serialize, Clone, Debug, Default)]
Expand Down Expand Up @@ -745,6 +765,11 @@ const DEFAULT_CONFIG: &str = r#"
"progress": {
"progressChars": "▨▨"
},
"duplicatePackageChecker": {
"verbose": false,
"showHelp": false,
"emitError": false,
},
"emitAssets": true,
"cssModulesExportOnlyLocales": false,
"inlineCSS": false,
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 @@ -3,6 +3,7 @@ pub mod bundless_compiler;
pub mod context_module;
pub mod copy;
pub mod detect_circular_dependence;
pub mod duplicate_package_checker;
pub mod emotion;
pub mod graphviz;
pub mod hmr_runtime;
Expand Down
199 changes: 199 additions & 0 deletions crates/mako/src/plugins/duplicate_package_checker.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,199 @@
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};

use semver::Version;

use crate::compiler::Context;
use crate::module_graph::ModuleGraph;
use crate::plugin::Plugin;
use crate::resolve::ResolverResource;

#[derive(Debug, Clone)]
struct PackageInfo {
name: String,
version: Version,
path: PathBuf,
}

#[derive(Default)]
pub struct DuplicatePackageCheckerPlugin {
verbose: bool,
show_help: bool,
emit_error: bool,
}

/// Cleans the path by replacing /node_modules/ or \node_modules\ with /~/
fn clean_path(module_path: &Path) -> PathBuf {
let path_str = module_path.to_string_lossy();
let cleaned_path = path_str
.replace("/node_modules/", "/~/")
.replace("\\node_modules\\", "/~/");
PathBuf::from(cleaned_path)
}

/// Makes the cleaned path relative to the given context
fn clean_path_relative_to_context(module_path: &Path, context: &Path) -> PathBuf {
let cleaned_path = clean_path(module_path);
let context_str = context.to_str().unwrap();
let cleaned_path_str = cleaned_path.to_str().unwrap();

if cleaned_path_str.starts_with(context_str) {
let relative_path = cleaned_path_str.trim_start_matches(context_str);
PathBuf::from(format!(".{}", relative_path))
} else {
cleaned_path
}
}

impl DuplicatePackageCheckerPlugin {
pub fn new() -> Self {
Self::default()
}

pub fn verbose(mut self, verbose: bool) -> Self {
self.verbose = verbose;
self
}

pub fn show_help(mut self, show_help: bool) -> Self {
self.show_help = show_help;
self
}

pub fn emit_error(mut self, emit_error: bool) -> Self {
self.emit_error = emit_error;
self
}

fn find_duplicates(packages: Vec<PackageInfo>) -> HashMap<String, Vec<PackageInfo>> {
let mut package_map: HashMap<String, Vec<PackageInfo>> = HashMap::new();

for package in packages {
package_map
.entry(package.name.clone())
.or_default()
.push(package);
}

package_map
.into_iter()
.filter(|(_, versions)| versions.len() > 1)
.collect()
}

fn check_duplicates(
&self,
module_graph: &RwLock<ModuleGraph>,
) -> HashMap<String, Vec<PackageInfo>> {
let mut packages = Vec::new();

module_graph
.read()
.unwrap()
.modules()
.iter()
.for_each(|module| {
if let Some(ResolverResource::Resolved(resource)) = module
.info
.as_ref()
.and_then(|info| info.resolved_resource.as_ref())
{
let package_json = resource.0.package_json().unwrap();
let raw_json = package_json.raw_json();
if let Some(name) = package_json.name.clone() {
if let Some(version) = raw_json.as_object().unwrap().get("version") {
let package_info = PackageInfo {
name,
version: semver::Version::parse(version.as_str().unwrap()).unwrap(),
path: package_json.path.clone(),
};

packages.push(package_info);
}
}
}
});

Self::find_duplicates(packages)
}
}

impl Plugin for DuplicatePackageCheckerPlugin {
fn name(&self) -> &str {
"DuplicatePackageCheckerPlugin"
}

fn after_build(
&self,
context: &Arc<Context>,
_compiler: &crate::compiler::Compiler,
) -> anyhow::Result<()> {
let duplicates = self.check_duplicates(&context.module_graph);

if !duplicates.is_empty() && self.verbose {
let mut message = String::new();

for (name, instances) in duplicates {
message.push_str(&format!("\nMultiple versions of {} found:\n", name));
for instance in instances {
let mut line = format!(" {} {}", instance.version, instance.name);
let path = instance.path.clone();
line.push_str(&format!(
" from {}",
clean_path_relative_to_context(&path, &context.root).display()
));
message.push_str(&line);
message.push('\n');
}
}

if self.show_help {
message.push_str("\nCheck how you can resolve duplicate packages: \nhttps://github.com/darrenscerri/duplicate-package-checker-webpack-plugin#resolving-duplicate-packages-in-your-bundle\n");
}

if !self.emit_error {
println!("{}", message);
} else {
eprintln!("{}", message);
}
}

Ok(())
}
}

#[cfg(test)]
mod tests {
use std::path::PathBuf;

use crate::config::{Config, DuplicatePackageCheckerConfig};
use crate::plugin::Plugin;
use crate::plugins::duplicate_package_checker::DuplicatePackageCheckerPlugin;
use crate::utils::test_helper::setup_compiler;

#[test]
fn test_duplicate_package_checker() {
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("test/build/duplicate-package");
let mut config = Config::new(&root, None, None).unwrap();
config.check_duplicate_package = Some(DuplicatePackageCheckerConfig {
verbose: true,
emit_error: false,
show_help: true,
});

let compiler = setup_compiler("test/build/duplicate-package", false);
let plugin = DuplicatePackageCheckerPlugin::new()
.verbose(true)
.show_help(true)
.emit_error(false);

// 运行编译
compiler.compile().unwrap();

// 执行插件的 after_build 方法
let result = plugin.after_build(&compiler.context, &compiler);

assert!(result.is_ok());
}
}
3 changes: 3 additions & 0 deletions crates/mako/test/build/duplicate-package/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
require('a');
require('b');
require('c');
6 changes: 6 additions & 0 deletions crates/mako/test/build/duplicate-package/mako.config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"duplicatePackageChecker": {
"verbose": true,
"showHelp": true
}
}

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

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

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

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

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

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

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

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

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

Loading