This is a follow-up of this blog post and this Mastodon discussion with @awbjs .
I would like to propose imports that only resolve iff there is at least one strong (=non-weak) import to the same module specifier, otherwise all their imported references are null.
The rationale is explained at length in the blog post, but in a nutshell: Libraries often need to be able to "enhance" their behavior if certain other dependencies are loaded, but can function without these dependencies. Right now it's all-or-nothing: either you import a dependency yourself and use it (and accept its contribution to the size of your dependencies), or you don't use it at all, or you expand your API surface and your users' cognitive overhead with special methods that they can use to connect a library they imported with your library.
Syntax-wise, @awbjs suggested piggybacking on the import assertions proposal. Possibly this could be done through a Boolean weak
property. I’m not sure if it's possible to have imports fail differently (null
instead of throwing) based on the values of import assertions, but this would combine nicely with the optional imports proposal.
For bare module specifiers, there's usually only one way to reference a given module, but when importing from URLs, there may often be several different URLs to refer to the same module.
Therefore, it may be good to allow several comma-separated specifiers in that syntax that will be tested in order, though this rules out import assertions, unless "specifier stacks" became a general part of ImportDeclaration
(which could be more broadly useful, but much less for strong imports).
Weak imports would be useful even without this, as it can be done manually by the author:
import? foo1 from "https://cdn.jsdelivr.net/npm/foo" assert { weak: true };
import? foo2 from "https://unpkg.com/foo" assert { weak: true };
const foo = foo1 ?? foo2;
Versioning is the obvious counterargument to this. How can an import be useful if you could get any version back?
Authors would need to be careful to check version numbers or feature detects, since they may get a different version of the module than they expect.
But this is no different than using built-in browser APIs.
They could even have multiple weak imports for multiple versioned URLs, and then they know which version they got.