【问题标题】:Import/export in JavaScript gives "Uncaught SyntaxError: Unexpected identifier"JavaScript 中的导入/导出给出“未捕获的语法错误:意外的标识符”
【发布时间】:2019-05-18 03:38:15
【问题描述】:

我有好几天都想不通的非常简单的问题。 我有 2 个 .js 文件。一是用于配置。我需要将 default.js 中的数据调用到 app.js 中。但它给 未捕获的 SyntaxError:意外的标识符

我检查了所有在线平台以找到解决方案,尝试了所有不同的导出/导入组合但找不到任何解决方案。

//default.js

export default (config = {
  apiKey: "enterYourApiKeyFromOpenWeather"
});

//app.js

import config from "./config/default";

我正在使用 vscode 并且 (import config from "./config/default";) 行带有下划线和空格。我可能需要安装一个包。

如果我写:

const config = require("./config/default");

我收到此错误: app.js:2 Uncaught ReferenceError: require is not defined

【问题讨论】:

  • jro,这不是 node.js 项目。它是普通的 javaScript。
  • 哦,我明白了,您是否在脚本元素上设置了type=module
  • 两个文件都是 .js 文件。我相信 type=module 当你想在
  • 我认为我之前的评论有误。我按照你的要求做了,但没有用:(

标签: javascript import configuration export frontend


【解决方案1】:

您需要在 default.js 导入中指定 .js,因为这是普通 JS,而不是构建过程(例如 Gulp)或 express.js 应用本身的一部分。

在你的app.js

import config from "./config/default.js";

如 jro 在 cmets 中提到的,在脚本元素中包含 app.js 时:

...您是否在脚本元素上设置了 type=module - jro

您需要在脚本和模块上设置type=module,例如:

<script src="app.js" type="module">
<script src="config/default.js" type="module">

如果你不指定type=module,你会再次遇到Uncaught SyntaxError: Unexpected identifier

【讨论】:

  • 我刚做了 Caleb,我得到了新生的错误:GET localhost:8000/config/default net::ERR_ABORTED 404 (Not Found) default.js:1 Uncaught ReferenceError: config is not defined at default.js:1 (匿名)@default.js:1
  • 将您的 default.js 重写为:export default config = { apiKey: "enterYourApiKeyFromOpenWeather" }; 从导出中删除括号,在导入时您需要将默认值导入为配置,因为您没有命名导出,您只是在导出默认:import { default as config } from "./config/default.js";您可以访问此处以进一步参考:[2ality.com/2014/09/es6-modules-final.html]
  • 导出默认是一个函数。即使我删除了括号,vscode 也会自动添加它们。我按照你的指示,我得到了另一个错误:default.js:4 Uncaught ReferenceError: config is not defined at default.js:4 。我认为问题可能出在 vscode 本身。因为我什么都试过了,但没有任何效果:(
  • 是的,你没有声明配置的类型。再试一次:const config = { apiKey: "enterYourApiKeyFromOpenWeather" } 是的,把你正确的括号保留在那里。所以你的 default.js 看起来像:export default (const config = { apiKey: "enterYourApiKeyFromOpenWeather" });
  • 我遇到了另一个错误:( Uncaught SyntaxError: Unexpected token const
猜你喜欢
  • 2020-06-20
  • 2023-03-20
  • 2018-10-10
  • 2013-11-28
  • 2015-06-15
  • 2013-11-28
  • 2019-12-23
相关资源
最近更新 更多