Hacker News new | ask | show | jobs
by davnicwil 1684 days ago
> for some completely unclear reason, ESM proponents decided to remove that property. There's just no way anymore to directly combine an import statement with some other JS syntax

This is one of those 'worse is better' things in language design, I believe. It guarantees simplicity, traded off against extra verbosity. In fact, when it comes to the common and probably most valuable case of reading and understanding code written by others quickly, it is not even a tradeoff really, as both are good.

Whether or not that was one of the driving reasons, it certainly is a benefit in my opinion. The two examples given in the post of an inline require don't demonstrate this well, as they're both really simple. I'd say the benefit isn't to stop things examples like that being written and replace them with two lines of code, which admittedly might sometimes be slightly cumbersome. It's that it stops the long tail of much more complex/unreadable statements being written.

2 comments

I would have considered this a valid argument if overly-clever use of `require` was actually a problem in JS. But it's not! These 'simple' types of obvious cases are the only types of cases that people actually use this syntax for in practice.
I have seen horrors of abuse of the CJS require cache, I’m glad to hear you haven’t had to deal with it.

For what it’s worth, whether it’s bitten you or not, every single instance of my sillycode[1] is in use in Jest (granted in obviously more useful ways). And it’s an enormous headache to debug when it goes wrong. A trivial example: require a logging library which creates a singleton at module definition time and provides no teardown API (yeah that sounds like a bad design but believe me they exist, are easy to find, and hard to replace on a busy and/or opinionated team). If you have a single suite with 100 tests, Jest will leave 100 instances of that singleton running and consuming memory even while totally idle, completely inaccessible to most any machination you might come up with to try to free them.

Which isn’t to say ESM doesn’t have this same problem if you try to bust the import cache with eg query parameters. But at least you’ll probably notice it’s a problem because you’re very probably doing it directly and not with some opaque Babel transform that hijacks the entire module system and any code referencing it.

1: https://news.ycombinator.com/item?id=29140847

Edit: forgot which sub thread I was in, added link to my sillycode

> This is one of those 'worse is better' things in language design, I believe. It guarantees simplicity, traded off against extra verbosity.

And with top-level await the restriction goes away (albeit the ESM equivalent is still a bit more verbose).

    (await import('anything'))(...yup)