Search code examples
javascriptecmascript-6es6-modules

Get the file name of the current ES module


Is it possible to get the file name of the current JavaScript module?

// item.mjs
function printName() {
  console.log(...);  // >> item or item.mjs
};

If not, why not? Sandboxing, etc.


Solution

  • You are looking for the (proposed) import.meta meta property. What exactly this object holds depends on the environment, but in a browser you can use

    // item.mjs
    function printName() {
      console.log(import.meta.url);  // https://domain.example/js/item.mjs
    }
    

    You can extract the file name by parsing that with the URL interface, e.g.

    console.log(new URL(import.meta.url).pathname.split("/").pop())