From 794d347ec68fa969ffed231d0844a59a215d2344 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bartek=20Iwa=C5=84czuk?= Date: Thu, 5 Sep 2024 13:49:07 +0100 Subject: fix: add suggestion how to fix importing CJS module (#21764) ``` $ cat exports_error.js Object.defineProperty(exports, "__esModule", { value: true }); $ deno exports_error.js error: Uncaught (in promise) ReferenceError: exports is not defined Object.defineProperty(exports, "__esModule", { value: true }); ^ at file:///exports_error.js:1:23 info: Deno doesn't support CommonJS modules without `.cjs` extension. hint: Rewrite this module to ESM or change the file extension to `.cjs`. ``` --- cli/main.rs | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) (limited to 'cli/main.rs') diff --git a/cli/main.rs b/cli/main.rs index 3b366306a..da274d8ed 100644 --- a/cli/main.rs +++ b/cli/main.rs @@ -46,7 +46,8 @@ use deno_core::error::JsError; use deno_core::futures::FutureExt; use deno_core::unsync::JoinHandle; use deno_npm::resolution::SnapshotFromLockfileError; -use deno_runtime::fmt_errors::format_js_error; +use deno_runtime::fmt_errors::format_js_error_with_suggestions; +use deno_runtime::fmt_errors::FixSuggestion; use deno_runtime::tokio_util::create_and_run_current_thread_with_maybe_metrics; use deno_terminal::colors; use factory::CliFactory; @@ -336,12 +337,30 @@ fn exit_with_message(message: &str, code: i32) -> ! { std::process::exit(code); } +fn get_suggestions_for_commonjs_error(e: &JsError) -> Vec { + if e.name.as_deref() == Some("ReferenceError") { + if let Some(msg) = &e.message { + if msg.contains("module is not defined") + || msg.contains("exports is not defined") + { + return vec![ + FixSuggestion::info("Deno does not support CommonJS modules without `.cjs` extension."), + FixSuggestion::hint("Rewrite this module to ESM or change the file extension to `.cjs`."), + ]; + } + } + } + + vec![] +} + fn exit_for_error(error: AnyError) -> ! { let mut error_string = format!("{error:?}"); let mut error_code = 1; if let Some(e) = error.downcast_ref::() { - error_string = format_js_error(e); + let suggestions = get_suggestions_for_commonjs_error(e); + error_string = format_js_error_with_suggestions(e, suggestions); } else if let Some(SnapshotFromLockfileError::IntegrityCheckFailed(e)) = error.downcast_ref::() { -- cgit v1.2.3