diff options
Diffstat (limited to 'cli/module_loader.rs')
-rw-r--r-- | cli/module_loader.rs | 35 |
1 files changed, 29 insertions, 6 deletions
diff --git a/cli/module_loader.rs b/cli/module_loader.rs index 4d3cfe27f..e280a8a3a 100644 --- a/cli/module_loader.rs +++ b/cli/module_loader.rs @@ -4,6 +4,7 @@ use crate::emit::emit_parsed_source; use crate::emit::TsTypeLib; use crate::graph_util::ModuleEntry; use crate::node; +use crate::node::CjsToEsmTranslateKind; use crate::npm::NpmPackageResolver; use crate::proc_state::ProcState; use crate::text_encoding::code_without_source_map; @@ -23,6 +24,7 @@ use deno_core::ModuleType; use deno_core::OpState; use deno_core::SourceMapGetter; use deno_runtime::permissions::Permissions; +use std::borrow::Cow; use std::cell::RefCell; use std::pin::Pin; use std::rc::Rc; @@ -134,30 +136,51 @@ impl CliModuleLoader { maybe_referrer: Option<ModuleSpecifier>, ) -> Result<ModuleSource, AnyError> { let code_source = if self.ps.npm_resolver.in_npm_package(specifier) { - let file_path = specifier.to_file_path().unwrap(); + let is_cjs = self.ps.cjs_resolutions.lock().contains(specifier); + let (maybe_translate_kind, load_specifier) = if is_cjs { + let path = specifier.path(); + let mut specifier = specifier.clone(); + if let Some(new_path) = path.strip_suffix(node::CJS_TO_ESM_NODE_SUFFIX) + { + specifier.set_path(new_path); + (Some(CjsToEsmTranslateKind::Node), Cow::Owned(specifier)) + } else if let Some(new_path) = + path.strip_suffix(node::CJS_TO_ESM_DENO_SUFFIX) + { + specifier.set_path(new_path); + (Some(CjsToEsmTranslateKind::Deno), Cow::Owned(specifier)) + } else { + // all cjs code that goes through the loader should have been given a suffix + unreachable!("Unknown cjs specifier: {}", specifier); + } + } else { + (None, Cow::Borrowed(specifier)) + }; + + let file_path = load_specifier.to_file_path().unwrap(); let code = std::fs::read_to_string(&file_path).with_context(|| { let mut msg = "Unable to load ".to_string(); msg.push_str(&*file_path.to_string_lossy()); - if let Some(referrer) = maybe_referrer { + if let Some(referrer) = &maybe_referrer { msg.push_str(" imported from "); msg.push_str(referrer.as_str()); } msg })?; - let is_cjs = self.ps.cjs_resolutions.lock().contains(specifier); - let code = if is_cjs { + let code = if let Some(translate_kind) = maybe_translate_kind { // translate cjs to esm if it's cjs and inject node globals node::translate_cjs_to_esm( &self.ps.file_fetcher, - specifier, + &load_specifier, code, MediaType::Cjs, &self.ps.npm_resolver, + translate_kind, )? } else { // only inject node globals for esm - node::esm_code_with_node_globals(specifier, code)? + node::esm_code_with_node_globals(&load_specifier, code)? }; ModuleCodeSource { code, |