所以我试图从youtube视频中学习模块,所以我和他一起学习,但是由于某种原因,我的代码与他的完全相同,并且给了我错误
SyntaxError: Cannot use import statement outside a module
我不确定是否是因为我的目录错误?我在此PC>桌面> 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>
我正在尝试import
从utils.js文件进行编码,该文件与main.js位于同一文件夹中,这是我的utils.js代码。
export function double(n){
return n * 2;
}
当我在main.js文件上运行代码时,出现错误: SyntaxError: Cannot use import statement outside a module
您需要运行自己的Web服务器。一个简单的方法就是获取适用于Chrome的Web服务器。您只需运行它,将其指向本地计算机文件夹,它将为您的计算机提供该文件夹的本地端口号。这样,您可以通过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". Relative references must start with either "/", "./", or "../"
,而URL错误的结果将导致404。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句