The case for Weak Dependencies in JS • Lea Verou
Earlier today, I was briefly entertaining the idea of writing a library to wrap and enhance querySelectorAll in certain ways. I thought I’d rather not introduce a Parsel dependency out of the box, but only use it to parse selectors properly when it’s available, and use more crude regex when it’s not (which would cover most use cases for what I wanted to do). In the olden days, where every library introduced a global, I could just do: if (window.Parsel) { let ast = Parsel.parse(); // rewrite selector properly, with AST } else { // crude regex replace } However, with ESM, there doesn’t seem to be a way to detect whether a module is imported, without actually importing it yourself. I tweeted about this… https://twitter.com/LeaVerou/status/1329389035249422336 I thought this was a common paradigm, and everyone would understand why this was useful. However, I was surprised to find that most people were baffled about my use case. Most of them thought I was either talking about conditional imports, or error recovery after failed imports. I suspect it might be because my primary perspective for writing JS is that of a library author, where I do not control the host environment, whereas for most developers, their primary perspective is that of writing JS for a specific app or website. After Kyle Simpson asked me to elaborate about the use case, I figured a blog post was in order. The use case is essentially progressive enhancement (in fact, I toyed with the idea of titling this blog post “Progressively Enhanced JS”). If library X is loaded already by other code, do a more elaborate thing and cover all the edge cases, otherwise do a more basic thing. It’s for dependencies that are not really dependencies, but more like nice-to-haves.
lea.verou.me