We can do this in Node.js fairly easily, but it would be useful to have in browsers too.
import {foo} from 'https://web.site/path/to/lib.js'
if (import.meta.isEntry) {
// if this is top level, we might show a demo of `doSomethingWithFoo`
console.log(doSomethingWithFoo(foo))
}
export function doSomethingWithFoo() {}
And likewise, we might need this:
import('https://web.site/path/to/lib.js', {
isEntry: true // false by default seems good for `import()`, otherwise it'll break existing import()s of libs that are not top-level entries (most of them probably)
})
Real-world example
A file like this one,
https://codepen.io/ScavengerFrontend/pen/xxGwjox.js
which is from this pen:
could replace this,
init();
render();
with
if (import.meta.isEntry) {
init();
render();
}
and it could additional prepend export
to createCactus
like this,
export function createCactus() {
The result would be that the pen works as a standalone demo, but any other pens (or any other ESM code anywhere on the internet) could import it and use the cactus shapes in their creations:
import {createCactus} from 'https://codepen.io/ScavengerFrontend/pen/xxGwjox.js'
const cactus = createCactus()
// ...