From 0223ad72a999d1237162a96228f568d973b115fb Mon Sep 17 00:00:00 2001 From: Elian Cordoba Date: Fri, 14 Jul 2023 13:47:18 -0300 Subject: fix(npm): improve error message on directory import in npm package (#19538) Co-authored-by: David Sherret --- cli/module_loader.rs | 33 +++++++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-) (limited to 'cli/module_loader.rs') diff --git a/cli/module_loader.rs b/cli/module_loader.rs index 9e814662c..54efcd9dd 100644 --- a/cli/module_loader.rs +++ b/cli/module_loader.rs @@ -748,13 +748,34 @@ impl NpmModuleLoader { .read_to_string(&file_path) .map_err(AnyError::from) .with_context(|| { - let mut msg = "Unable to load ".to_string(); - msg.push_str(&file_path.to_string_lossy()); - if let Some(referrer) = &maybe_referrer { - msg.push_str(" imported from "); - msg.push_str(referrer.as_str()); + if file_path.is_dir() { + // directory imports are not allowed when importing from an + // ES module, so provide the user with a helpful error message + let dir_path = file_path; + let mut msg = "Directory import ".to_string(); + msg.push_str(&dir_path.to_string_lossy()); + if let Some(referrer) = &maybe_referrer { + msg.push_str(" is not supported resolving import from "); + msg.push_str(referrer.as_str()); + let entrypoint_name = ["index.mjs", "index.js", "index.cjs"] + .iter() + .find(|e| dir_path.join(e).is_file()); + if let Some(entrypoint_name) = entrypoint_name { + msg.push_str("\nDid you mean to import "); + msg.push_str(entrypoint_name); + msg.push_str(" within the directory?"); + } + } + msg + } else { + let mut msg = "Unable to load ".to_string(); + msg.push_str(&file_path.to_string_lossy()); + if let Some(referrer) = &maybe_referrer { + msg.push_str(" imported from "); + msg.push_str(referrer.as_str()); + } + msg } - msg })?; let code = if self.cjs_resolutions.contains(specifier) { -- cgit v1.2.3