Skip to content

🥇 Deno's import.meta.main for Node.js and the browser

License

Notifications You must be signed in to change notification settings

web4more/import-meta-main

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

53 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

import.meta.main for Node.js

Installation

npm install @denofill/import-meta-main
import {} from "https://esm.sh/@denofill/import-meta-main";

Usage

import polyfill from "@denofill/import-meta-main";
polyfill(import.meta);

if (import.meta.main) {
  console.log("Hello from the CLI!");
} else {
  console.debug("Hello from a module!");
}

Don't worry about cross-environment compatibility. This polyfill is a no-op in Deno and Bun (which already have native support for import.meta.main).

Caveats

This works in Node.js main thread, Node.js worker threads, Node.js --loader threads, window, Worker, SharedWorker, and service worker contexts. That notably omits Worklet contexts (from the CSS worklet and audio worklet APIs). Why? Because these contexts don't expose any hints as to what the top-level script was (no location).

When operating in a window context with a document, the isMain() check will properly resolve all <script src="https://..."> URLs to their final post-3XX redirected URL. This comes at the cost of doing this synchronously. If you'd like to contribute an isMainAsync() function, that'd be great! ❤️

Development

npm install
npm test
npm test:browser

About

🥇 Deno's import.meta.main for Node.js and the browser

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • JavaScript 72.9%
  • HTML 27.1%