簡體   English   中英

從外部 html 導入腳本內部的本地模塊

[英]Import local module inside of script from external html

我有前端和后端。 從后端我得到預渲染的 html (Symfony 形式),其中包括帶有源標簽的腳本。 來源是本地主機:8001。

<html>
    <head>
        ...
    </head>
    <body>
        ...
        <div class="container">
            {% block javascripts %}
                <script type="module" src="http://localhost:8020/build/form_generator/script.js"></script>
            {% endblock %}
        </div>
    </body>
</html>

在前端 (localhost:8020) script.js 位於 Public 文件夾中。 腳本加載正常,但在腳本內部我想從前端加載另一個模塊(Select2,安裝到 node_modules)但我無法正確加載它。 Select2 在前端的其他腳本中正確導入。 腳本.js:

/** @module script*/

  import 'select2'; // gives log error 1
  import select2 from "../../../node_modules/select2/dist/js/select2"; // gives log error 2

日志錯誤 1:未捕獲的 TypeError:無法解析模塊說明符“select2”。 相對引用必須以“/”、“./”或“../”開頭。

日志錯誤2:GET http://localhost:8020/node_modules/select2/dist/js/select2 net::ERR_ABORTED 404(未找到)

瀏覽器加載的模塊不能使用 Node.JS 模塊解析規則。

他們無權訪問文件系統。 他們無法搜索node_modules目錄。

你需要:

  • 確保您要加載的模塊具有 URL(如何執行此操作取決於您的 HTTP 服務器)
  • 導入URL

例如

import select2 from '/static/js/select2.js';

或者,使用可以執行 Node.js 模塊解析的捆綁程序(例如 Webpack 或 Parcel)將所有模塊捆綁到一個 JS 文件中,您可以將其作為非模塊加載。

暫無
暫無

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

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