无法在模块外部使用 import 语句(位于index.js:1:1)

问题描述 投票:0回答:1

我最近开始学习 JS,我正在尝试将函数从模块脚本导出到我的主“index.js”脚本。但我收到“未捕获的语法错误:无法在模块外部使用导入语句(位于index.js:1:1)”错误。

有人可以帮我吗?

我尝试过使用 type = module。我不确定我做错了什么。我尝试在 Chrome 和 Edge 中运行代码,同样的错误。

index.html

<!DOCTYPE html>
<html lang="en">

<head>
  <script src="./shoppingCart.js" type="module"></script>
  <script defer src="./index.js"></script>
  <title>Modern JavaScript Development: Modules and Tooling</title>
</head>

<body>
  <h1>Modern JavaScript Development: Modules and Tooling</h1>
</body>

</html>

index.js

import * as shoppingCart from "./shoppingCart.js";
shoppingCart.addToCart("iPhone", 1);

shoppingCart.js

export const addToCart = function (product, quantity) {
  console.log(`${quantity} ${product} added to the cart.`);
};
javascript es6-modules
1个回答
0
投票

您只能在 ES 模块内使用

import

由于您在

import
中使用
index.js
,因此您需要告诉浏览器它也是一个模块(以及
shoppingCart.js
)。

因此,您需要将

type="module
添加到加载索引文件的
src
元素。

© www.soinside.com 2019 - 2024. All rights reserved.