From a65ce33fabb44bb2d9ed04773f7f334ed9c9a6b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartek=20Iwa=C5=84czuk?= Date: Sun, 27 Feb 2022 14:38:45 +0100 Subject: feat(compat): CJS/ESM interoperability (#13553) This commit adds CJS/ESM interoperability when running in --compat mode. Before executing files, they are analyzed and all CommonJS modules are transformed on the fly to a ES modules. This is done by utilizing analyze_cjs() functionality from deno_ast. After discovering exports and reexports, an ES module is rendered and saved in memory for later use. There's a caveat that all files ending with ".js" extension are considered as CommonJS modules (unless there's a related "package.json" with "type": "module"). --- cli/graph_util.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) (limited to 'cli/graph_util.rs') diff --git a/cli/graph_util.rs b/cli/graph_util.rs index f0a38b7a1..4b01f54e0 100644 --- a/cli/graph_util.rs +++ b/cli/graph_util.rs @@ -53,6 +53,7 @@ pub(crate) struct GraphData { /// error messages. referrer_map: HashMap, configurations: HashSet, + cjs_esm_translations: HashMap, } impl GraphData { @@ -254,6 +255,7 @@ impl GraphData { modules, referrer_map, configurations: self.configurations.clone(), + cjs_esm_translations: Default::default(), }) } @@ -412,6 +414,27 @@ impl GraphData { ) -> Option<&'a ModuleEntry> { self.modules.get(specifier) } + + // TODO(bartlomieju): after saving translated source + // it's never removed, potentially leading to excessive + // memory consumption + pub(crate) fn add_cjs_esm_translation( + &mut self, + specifier: &ModuleSpecifier, + source: String, + ) { + let prev = self + .cjs_esm_translations + .insert(specifier.to_owned(), source); + assert!(prev.is_none()); + } + + pub(crate) fn get_cjs_esm_translation<'a>( + &'a self, + specifier: &ModuleSpecifier, + ) -> Option<&'a String> { + self.cjs_esm_translations.get(specifier) + } } impl From<&ModuleGraph> for GraphData { -- cgit v1.2.3