Maury8788
Maury8788

Reputation: 53

Javascript library without using an import in the script tag

I try to create a library using typescript and I would like to use a static method that allows me to render some HTML content that is returned to me by an api rest call based on the parameters I pass to that function now there is a way to create it using a architecture eg pattern repository, compile it and then use it as in the code below (in js format of course)?

<div id="test"></div>

<script scr="../myLybrary.js"></script>
<script type="module">

    MyLibrary.render({
        param: "test",
        param1: "test",
        param2: "test"
    }, "test")

</script>

at the moment to create this situation I have to use an import in the script where the call to the static method resides in this way:

import MyLibrary from './myLybrary.js'

is there any way to avoid this last step?

Thanks to anyone who wants to help me.

Upvotes: 2

Views: 1768

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074385

at the moment to create this situation I have to use an import in the script where the call to the static method resides in this way:

import MyLibrary from './myLybrary.js'

That would generally be the right thing to do. You'd just remove the first script tag, since with it you'll end up loading your library twice. So that leaves us with:

<div id="test"></div>

<!-- Note: No `script` tag for `myLybrary.js` here. -->
<script type="module">
    import MyLibrary from "./myLybrary.js";

    MyLibrary.render({
        param: "test",
        param1: "test",
        param2: "test"
    }, "test");

</script>

Loading a module runs the top-level code in the module, so if myLybrary.js has top-level code that loads some resource, that code will be run when the import declaration is processed.

Upvotes: 2

Related Questions