我正在尝试从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语句
npx ucdn --debug
并在该地址上进行测试,或者使用任何其他一行命令的服务器端,而不是将HTML页面作为文件运行。 - Andrea Giammarchi