`import.meta.isEntry` to detect top-level root module(s)

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`

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,


which is from this pen:

could replace this,



if (import.meta.isEntry) {

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()

// ...

I've created a workaround to achieve something like this specifically for my codepen demos. For example, in this pen, I define a few custom elements for rendering flickering lights:

Note at the bottom of the JS it has this, which is in a similar vein:

// Run code only if this script is running in this pen. Otherwise other pens may import the above.
if (document.querySelector("#YzGbeKG")) {
	lights.rotation = (x, y, z) => [x, y + 0.2, z];

Then here's another pen,

that imports the light elements,

import "https://codepen.io/trusktr/pen/YzGbeKG.js?4";

and places them around a different object

Considering how it's generally become a bad practice to do this in node - eg, to have a file that doubles as an entry point and as an importable thing - I think the best thing to do here is continue to encourage having single-purpose files.

1 Like

Some prior conversation on this topic here: Add `import.meta` · Issue #46 · wintercg/proposal-common-minimum-api · GitHub