javascript - 错误 : "Unexpected token ' {'. Import call expects exactly one argument" when trying to import functions from a script

标签 javascript import safari importerror

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

这些文件被命名为“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()”。

任何帮助将不胜感激。

最佳答案

您必须在页面上正确包含一个脚本,显示脚本类型为“模块”:

<script src="/js/index.js" type="module"></script>
如果浏览器不支持模块,您可以使用“nomodule”属性简单地处理它:
<script nomodule>
  console.info(`Your browser doesn't support native JavaScript modules.`);
</script>

关于javascript - 错误 : "Unexpected token ' {'. Import call expects exactly one argument" when trying to import functions from a script,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54392611/

相关文章:

safari - 如何以编程方式打包 Safari 扩展?

Postgresql - 将导入时的 csv 时间和日期合并到时间戳

ios - ipad safari 等浏览器应用程序中的新标签栏功能

javascript - 加载本地文件时出现 "Cross origin requests are only supported for HTTP."错误

javascript - 检查对象值是否等于字符串值

javascript - 如何使用 type=module 脚本中的代码

javascript - 我们在导入未使用的 JS 模块时会出现 "lose"吗?

jquery - $(window).load Chrome,Safari问题

javascript - 使用 Not Null 将 findAll 序列化

javascript - 文本悬停超链接