diff options
author | Bartek IwaĆczuk <biwanczuk@gmail.com> | 2024-09-05 13:49:07 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2024-09-05 12:49:07 +0000 |
commit | 794d347ec68fa969ffed231d0844a59a215d2344 (patch) | |
tree | 237b26bba35eb570683de86f68e0bff9bde162dd /cli/main.rs | |
parent | dda63287456aae5cd4f7f428e23b52cb8c0005e5 (diff) |
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`.
```
Diffstat (limited to 'cli/main.rs')
-rw-r--r-- | cli/main.rs | 23 |
1 files changed, 21 insertions, 2 deletions
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<FixSuggestion> { + 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::<JsError>() { - 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::<SnapshotFromLockfileError>() { |