我正在尝试使用以下语句将 JSON 文件导入 JavaScript
import phone_numbers from "./phoneNumbers.json";
JavaScript 文件作为模块加载到我的 HTML 文件中,如下所示
<script type="module" src="./scripts/main.js"></script>
当我查看该页面时,出现以下错误
TypeError: 'application/json' is not a valid JavaScript MIME type.
我尝试过这样导入
import phone_numbers from "./phoneNumbers.json" assert { type: "json" };
但是我收到以下错误
SyntaxError: Unexpected identifier 'assert'. Expected a ';' following a targeted import declaration.
如何正确地将 json 文件导入 JavaScript 文件
提前致谢
最佳答案
有四个基本选项。
使用 Node.js 和 CommonJS
const phone_numbers = require("./phoneNumbers.json");
由于您使用的是浏览器,因此这不适合您。
使用 JSON 模块
您需要支持the proposed JSON module specification的东西如Node.js以及正确的语法:
import phone_numbers from "./phoneNumbers.json" assert { type: 'json' };
预处理 JSON
像Webpack这样的工具可以处理 import ... .json'
语句并将 JSON 捆绑到应用程序中。
改用 Ajax
const response = await fetch("/url/to/phoneNumbers.json");
const phone_numbers = await response.json();
您需要使用支持顶级 await
的工具,或者将代码移至 async
函数内。
关于javascript - 类型错误 : 'application/json' is not a valid JavaScript MIME type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73634587/