簡體   English   中英

如何在普通 HTML 中導入 Javascript 模塊?

[英]How to import a Javascript module in plain HTML?

我的情況如下:

我想試用 Azure 通信服務 UI 庫中的一些組件:( https://azure.github.io/communication-ui-library/?path=/docs/quickstarts-composites--page )。 問題是:我想在有點遺留的代碼庫中使用它們(比方說舊版本的 ASP.NET),所以我無法以 React/Angular 方式導入模塊。 我可能需要以普通 HTML 導入它們。

我的想法是:我可以創建一個單獨的“site.js”文件,在其中導入模塊並將其加載到主 _Layout.cshtml 中。

我寫了這個腳本:

// 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);

然后像這樣導入腳本:

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

但這給了我錯誤:“未捕獲的語法錯誤:無法在模塊外使用導入語句”。 顯然這是不可能的。

所以我的問題是:這有可能嗎? 還有哪些方法可以嘗試?

您需要將您的 JS 作為模塊來獲取,這需要將type="module"添加到script節點:

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

取自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules#applying_the_module_to_your_html 整個頁面可能值得一讀。

您只能在模塊內部使用importexport語句,而不能使用常規腳本

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM