Home > Mobile >  How to import a Javascript module in plain HTML?
How to import a Javascript module in plain HTML?

Time:01-27

my situation is as follows:

I want to try out some components from the Azure Communication Services UI Library: (https://azure.github.io/communication-ui-library/?path=/docs/quickstarts-composites--page). The thing is: I want to use them in codebase that is kind of legacy (let's say an older version of ASP.NET), so there is no way I can import the modules in a React/Angular-way. I would probably need to import them in plain HTML.

My idea was: I can create a separate 'site.js' file, import the module in there and load this in the main _Layout.cshtml.

I wrote this script:

// TODO: How can we import this module?
import { Chat } from "@azure/communication-chat";

const chat = new Chat({
    auth: {
        token: "Your token here"
    },
    conversationId: "Your conversation Id here",
});

const chatContainer = document.getElementById("chat-container");
chat.render(chatContainer);

And then imported the script like this:

<script src="~/js/site.js" asp-append-version="true"></script>

But that gives me the error: "Uncaught SyntaxError: Cannot use import statement outside a module". Apparently it is not possible this way.

So my question is: Is it possible at all? What other ways are there to try?

CodePudding user response:

JavaScript modules are a way to organize and reuse code in JavaScript. In order to import a JavaScript module in plain HTML, you will need to use the tag and specify the src attribute to point to the file that contains the module.

Here's an example of how to import a JavaScript module called "myModule.js" in an HTML file:

<!DOCTYPE html>
<html>
<head>
  <title>Importing JavaScript Module</title>
</head>
<body>
  <script type="module" src="myModule.js"></script>
  <script>
    // You can now use the imported module here
    import { myFunction } from './myModule.js';
    myFunction();
  </script>
</body>
</html>

It's important to note that the type attribute of the tag should be set to "module" when importing JavaScript modules in HTML, this allows the browser to handle the modules correctly.

Also, you may need to use ./ or ../ to specify the path of the module if it is not in the same directory as the HTML file.

It's worth to mention that this way of importing modules is supported by modern browsers, if you are targeting older browsers you may need to use transpilers like Babel or TypeScript to convert your JavaScript modules to a version of JavaScript that is compatible with older browsers.

Also, you could use module bundlers like webpack or rollup that would bundle all your javascript files into one file, then you could import the bundled file into your HTML.

  • Related