首页 > 解决方案 > 错误:尝试从脚本导入函数时出现“意外的令牌 '{'。导入调用只需要一个参数”

问题描述

我已经设置了一个 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()”。

任何帮助将不胜感激。

标签: javascriptimportsafariimporterror

解决方案


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

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

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

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

推荐阅读