tsx icon indicating copy to clipboard operation
tsx copied to clipboard

Is it possible to catch a build-time error during a dynamic import?

Open thelinuxlich opened this issue 1 year ago • 1 comments

Precheck

  • [X] I searched existing issues before opening this one to avoid duplicates
  • [X] I understand tsx aims for TypeScript parity and will not support arbitrary Node.js enhancements
  • [X] This request cannot be made to Node.js directly, and is specific to tsx
  • [X] I understand this form is not for addressing a bug or seeking help

Feature request

I have a codegen task watching a directory for changes and whenever there is a malformed TS file, TSX will throw a esbuild error and exit the watcher. I wish I could try-catch this error so the watcher restarts the task.

Motivations

I don't know if it's expected but I think it's a bit unintuitive that I can't trust this:

try {
   await import('./something')
} catch (e) {
   console.log(e)
}

Alternatives

No response

Additional context

No response

Contributions

  • [ ] I plan to open a pull request for this issue
  • [ ] I plan to make a financial contribution to this project

thelinuxlich avatar Feb 06 '24 15:02 thelinuxlich

Not really sure what you're asking/reporting

privatenumber avatar Feb 06 '24 18:02 privatenumber

Also have this issue. I'm dynamically importing a path, and if that file has a syntax error in it, the watcher will crash and I need to restart the whole process.

In Node, you can catch the error like so:

try {
  const x = await import(`./file-with-syntax-error.js`);
  console.log(x);
} catch (e) {
  console.log(`caught error in try/catch block`);
  console.error(e);
}

But with tsx, esbuild throws and error and exits the process:

Screenshot 2024-03-13 at 3 04 16 PM

I supposed I could run nodemon or something to get around this, but was wondering if I could somehow catch the error on a dynamic require/import.

wesbos avatar Mar 13 '24 19:03 wesbos

Ooh gotcha. The original issue didn't explain that dynamic import errors can't be caught. Thanks for explaining.

This would be a bug, and possibly related to https://github.com/privatenumber/tsx/issues/493

Feel free to submit a PR

privatenumber avatar Mar 13 '24 19:03 privatenumber

Okay thank you - that is also the issue i have. I think we can close this as a dupe.

wesbos avatar Mar 13 '24 19:03 wesbos