Search code examples
javascriptreactjsasp.netazureazure-communication-services

How to import a Javascript module in plain HTML?


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?


Solution

  • You need to source your JS as a module, which requires adding type="module" to the script node:

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

    Taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules#applying_the_module_to_your_html. The whole page is probably worth reading.

    You can only use import and export statements inside modules, not regular scripts