nodejs / nodejs/node

Dynamic import does not show location of SyntaxError

Open
#49,441 38 comments 14 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

errors esm promises
Dominant language
JavaScript
Stars
122k
Forks
37.3k
Avg merge
4d 2h
Merged PRs (30d)
283

Description

// syntax-error.mjs
console.log([
  'str1'
  'str2'
]);

Perform a dynamic import with node -e "import('./syntax-error.mjs').catch(console.error)", the output does not help identify the error and could be seen by users as if node.js itself had a SyntaxError:

SyntaxError: Unexpected string
    at Loader.moduleStrategy (internal/modules/esm/translators.js:83:18)
    at async link (internal/modules/esm/module_job.js:37:21)

Now create and run a loader.mjs script:

import './syntax.mjs';

Running loader.mjs produces useful output:

file:///usr/src/npm/failures/syntax-error.mjs:3
	'str2'
	^^^^^^

SyntaxError: Unexpected string
    at Loader.moduleStrategy (internal/modules/esm/translators.js:83:18)

I was not able to find a way to catch the error of a dynamic import and show the complete SyntaxError. Interestingly node --unhandled-rejections=strict -e "import('./syntax-error.mjs')" or running await import('./syntax-error.mjs') from node --experimental-repl-await both display the location of the SyntaxError.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the dynamic-import case with the commands and syntax-error.mjs example. Start by tracing the paths shown in internal/modules/esm/translators.js and internal/modules/esm/module_job.js, comparing dynamic import with static import and strict unhandled rejections. Done means a caught dynamic-import SyntaxError includes the source location and offending code context.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, nodejs
Domain
backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Quiet
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.