JavaScript模块语法错误:无法在模块外部使用import语句。

3

我正在尝试从YouTube视频中学习模块的知识,并跟随其中的教程。但是,我的代码与他的完全相同,却报错了:

SyntaxError: Cannot use import statement outside a module

我不确定是否是因为我的目录设置有误?我的文件路径如下: This PC > Desktop > Javascript > module > 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>

我试图从与 main.js 相同文件夹中的 utils.js 文件导入代码。这是我的 utils.js 代码。
export function double(n){
    return n * 2;
}

当我在main.js文件上运行代码时,出现了错误:SyntaxError: 无法在模块外使用import语句


2
让我猜猜...你在测试时没有运行Web服务器...如果文件的MIME类型不正确,浏览器将无法识别这些文件。使用npx ucdn --debug并在该地址上进行测试,或者使用任何其他一行命令的服务器端,而不是将HTML页面作为文件运行。 - Andrea Giammarchi
1个回答

2
您需要运行自己的Web服务器。一个简单的方法是使用Chrome Web服务器。您只需运行它,将其指向本地计算机文件夹,它将为您提供一个本地主机端口号,您可以通过HTTP访问该文件夹。这样,您就可以通过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 -- 相对路径标记./是必须的。

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”。相对引用必须以“/”,“./”或“../”开头”,而错误的URL会导致404。

1
我很感激你的回答,实际上我在发布这个问题的当天就已经解决了。但是,如果其他人遇到同样的问题并且看到了这篇帖子,现在有一个官方答案是非常好的。我个人使用了来自Github的http-server/http-party来设置我的本地服务器。不过这个方法也应该可以!谢谢。 - Reid Riddle

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接