Javascript Modules SyntaxError: Cannot use import statement outside a module

Javascript Modules SyntaxError: Cannot use import statement outside a module

所以我正在尝试从 youtube 视频中学习模块,我正在跟随他,但出于某种原因,我的代码与他的代码完全相同,并且给我错误

SyntaxError: Cannot use import statement outside a module

我不确定是不是因为我的目录有误?我有它在 这台电脑 > 桌面 > Javascript > 模块 > js > main.js 这是来自 main.js

的代码
import{double} from './utils.js'

console.log(double(5))

我在模块文件夹中还有一个 index.html 文件 这是我的 index.html 代码。

<!DOCTYPE html>
<head>
    <title>JavaScript Modules</title>
    <meta name="viewport" content="width=device-width, initial scale=1.0">
    <meta charset="utf-8">
    <link rel="stylesheet" href="/assets/dcode.css">
    <link rel="shortcut icon" href="/assets/favicon.ico" type="image/x-icon">
</head>

<body>
    <h1>JavaScript Modules</h1>
    <u1>
        <li>Split up your code into separate components</li>
        <li>Therefore easier to maintain and organize</li>
        <li>Supported in major browsers(excl. IE)</li>
    </u1>

    <script type="module" src="./js/main.js"></script>
</body>

我正在尝试从我的 utils.js 文件中 import 代码,该文件与 main.js 位于同一文件夹中 这是我的 utils.js 代码。

export function double(n){
    return n * 2;
}

当我 运行 main.js 文件中的代码是我收到错误的地方: SyntaxError: Cannot use import statement outside a module

您需要 运行 您自己的网络服务器。一个简单的方法是获得 Web Server for Chrome。您只需 运行 它,将其指向您的本地计算机文件夹,它就会为您提供计算机为该文件夹提供服务的本地主机端口号。这样您就可以通过 HTTP 访问您的本地文件夹。

具有以下文件夹结构:

/exports/
   user.html
   importer.js
   exporter.js

其中 user.html 是使用 importer.js 脚本的页面,该脚本依次加载 exporter.js,您使用以下语法:

user.html -- type="module" 符号是必需的。

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

importer.js -- ./ relative notation is obligatory.

import { doStuff } from './exporter.js'

doStuff()

exporter.js -- 在生产环境中,这是您的库或模块。

function doStuff() {
   console.log('Do stuff')
}

export { doStuff }

对于本地服务器,上述设置将在控制台中记录 Do stuff

忘记 type="module" 会导致 Uncaught SyntaxError: Cannot use import statement outside a module,没有亲戚 URL 会导致 Uncaught TypeError: Failed to resolve module specifier "exporter.js". Relative references must start with either "/", "./", or "../",错误的 URL 会导致404.