Alex Gusev
Alex Gusev

Reputation: 1854

Get URL for EcmaScript module after importing in browser

My start HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <script type="module" src="/way/to/app.js" defer></script>
</head>
<body>...</body>
</html>

My app.js script is an EcmaScript Module and loads another EcmaScript Module:

import Mod from "./path/to/module.js";
...

this is module.js:

// const url = ???

export default class Module {
    constructor() {
        // console.log(url);
    }
}

Does exist any method to get loading URL "/way/to/path/to/module.js" in module.js? Something like these variables in nodejs but for browser:

const dir = __dirname;
const file = __filename;

location.href gives an URL for start html page.

Upvotes: 0

Views: 64

Answers (1)

Tom&#225;š Zato
Tom&#225;š Zato

Reputation: 53139

Google Chrome and Firefox both support import.meta:

<script type="module">
console.log(import.meta);
</script>

In my console that prints:

Object { url: "file:///D:/testImportMeta.html" }

I think it's not really suited for production, unless Babel supports it. But if you're not over-concerned with lazy browsers, it works well.

It does not work in Node.JS yet.

Upvotes: 2

Related Questions