[英]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
目錄。
你需要:
例如
import select2 from '/static/js/select2.js';
或者,使用可以執行 Node.js 模塊解析的捆綁程序(例如 Webpack 或 Parcel)將所有模塊捆綁到一個 JS 文件中,您可以將其作為非模塊加載。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.