You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在HTML中引入内部导入了JSON文件的JS模块

HTML导入含JSON引用的JS模块时MIME类型报错处理

我不是英语母语使用者,英语水平不佳但我已尽力表述问题。

我想要在HTML中引入一个内部导入了JSON文件的JS文件,相关代码如下:

相关代码

JS文件代码

import JSON from '../json/menu.json';

(function () {
  function parseMenu(ul, menu) {
    for (var i=0;i<menu.length;i++) {
      if(menu.sub == null) {
        menu.sort(function(a, b) {
          return a.id > b.id ? -1 : a.id > b.id ? 1 : 0;
        });
      }
      var li=$(ul).append('<li><a href="'+menu[i].link+'">'+menu[i].name+'</a></li>');
      if (menu[i].sub!=null) {
        var subul=$('<ul id="submenu'+menu[i].link+'"></ul>');
        $(li).append(subul);
        parseMenu($(subul), menu[i].sub);
      }
    }
  }
  var menu=$('#menu');
  parseMenu(menu, JSON);
});

JSON文件结构

[ {
     {
     },
     {
     }
   },
   {
     {
     },
     {
     }
   },
   {
   }
]

初始HTML引入写法

<script type="module" src="../js/left.js"></script>
<script type="module" src="../json/menu.json"></script>

报错信息

运行后收到如下报错:

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "application/json". Strict MIME type checking is enforced for module scripts per HTML spec.
中文释义:模块脚本加载失败:预期为JavaScript模块脚本,但服务器返回的MIME类型为application/json。根据HTML规范,模块脚本执行严格的MIME类型校验。

解决步骤

  • 将JS代码中的变量名JSON修改为menus
  • 删除HTML中多余的<script type="module" src="../js/left.mjs"></script>引入语句
  • 将JS代码中的导入语句import JSON from '../json/menu.json';修改为import menus from '../json/menus.json' assert { type: "json" };

内容的提问来源于stack exchange,提问作者Youn eciohc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 03:45:02