【问题标题】:Error: "Unexpected token '{'. Import call expects exactly one argument" when trying to import functions from a script错误:尝试从脚本导入函数时出现“意外的令牌 '{'。导入调用只需要一个参数”
【发布时间】:2019-01-27 20:34:33
【问题描述】:

我设置了一个 html 页面,其中包含一个按钮,单击该按钮会激活外部 javascript 文件中的功能。有问题的 JS 文件从另一个 JS 文件导入另外两个函数。但是,当我在浏览器(Safari 12.0.2)中加载 html 文件并在调试器中查看它时,我收到一条错误消息,指出“SyntaxError: Unexpected token '{'. import call 需要一个参数。”

文件名为“html_test_run.html”、“test_run_javascript.js”和“export_test_run.js”。我尝试将脚本的类型设置为“模块”,但这只会导致一个新错误,即“Access-Control-Allow-Origin 不允许使用 Origin null”。我还尝试使用三个 html 标记,前两个具有 js 文件的来源,第三个定义了按钮将使用的新函数,但也不起作用。

<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Test run</title>
    <meta name="description" content="Test run">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!--
    <link rel="stylesheet" href="">
  -->
  <script type="text/javascript" src="assets/test_run_javascript.js">
  </script>
  </head>
  <body>
      <button type="button" name="button" onclick="doSomething()">Click me</button>
  </body>
</html>

第一个 JS 文件:

import {doSomethingElse1, doSomethingElse2} from "export_test_run.js";
function doSomething(){
  doSomethingElse1();
  doSomethingElse2();
  console.log("Test successful");
}

第二个JS文件:

function doSomethingElse1(){
  console.log("Test successful1");
}

function doSomethingElse2(){
  console.log("Test successful2");
}

export {doSomethingElse1, doSomethingElse2};

我预计文件会正确加载,并且按钮会在单击时调用函数“doSomething()”。

任何帮助将不胜感激。

【问题讨论】:

  • @RichardSocker 谢谢,但是当我尝试按照示例并将 type="module" 放在脚本标记中并在“export_test_run.js”和“assets/test_run_javascript”前面添加“./”时。 js”分别在文件 test_run_javascript 和 html_test_run.html 中,我现在收到错误“Access-Control-Allow-Origin 不允许 Origin null”。另外我忘了提到所有文件都在我的 HD 上,以防万一导致问题。
  • @RichardSocker 我会对您的建议感兴趣。我使用两个 Javascript 文件的原因是第二个文件“export_test_run.js”是一个库(有点),其中包含文件“test_run_javascript.js”(以及最终的其他几个 JS 文件)使用的函数。

标签: javascript import safari importerror


【解决方案1】:

您必须在页面上正确包含一个脚本,表明该脚本类型是“模块”:

<script src="/js/index.js" type="module"></script>

如果浏览器不支持模块,你可以简单地使用“nomodule”属性来处理:

<script nomodule>
  console.info(`Your browser doesn't support native JavaScript modules.`);
</script>

【讨论】:

    【解决方案2】:

    您可以在第一页中包含您的两个 js 文件:

      <script type="text/javascript" src="export_test_run.js">
      </script>
      <script type="text/javascript" src="assets/test_run_javascript.js">
      </script>
    

    从您的 js 文件中删除导出和导入代码! 使用正确的包含路径。

    【讨论】:

      猜你喜欢
      • 2022-10-25
      • 1970-01-01
      • 2017-10-20
      • 2021-06-08
      • 2023-01-27
      • 2020-10-27
      • 1970-01-01
      • 1970-01-01
      • 2018-12-10
      相关资源
      最近更新 更多