gpt4 book ai didi

javascript - 导入类导致错误 : Uncaught syntaxerror unexpected identifier

转载 作者:行者123 更新时间:2023-11-30 13:58:05 25 4
gpt4 key购买 nike

我尝试将我的 Java 类 yellow.js 导入我的 index.js 并得到

"Uncaught syntaxerror unexpected identifier"

经过一些谷歌搜索后,我得到了更改我的建议

<script src="src/index.js"></script>

进入

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

但这会导致:

Access to script at 'file:///D:/Game/src/index.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https

我的代码现在看起来像这样:

index.html

    <html>

<head>
<title>Title</title>
<meta charset="UTF-8">

<style>
#gameScreen {
border: 1px solid black;
}
</style>

</head>

<body>
<canvas id="gameScreen" width='600' height='600'></canvas>
<script type="module" src="src/index.js"></script>
</body>

</html>

索引.js

    import Yellow from "/src/yellow";

let canvas = document.getElementById("gameScreen");
let ctx = canvas.getContext("2d");


let yellow = new Yellow();
yellow.draw();

黄色.js

    export default class yellow{
draw(ctx) {
ctx.fillStyle = '#ff0';
ctx.fillRect(20, 20, 100, 50);
}
}

我错过了什么吗?

我真的不明白在哪里以及如何添加 "type="module"

最佳答案

在浏览器上,模块名称必须有它们的扩展名(所以是 yellow.js,而不是 yellow),除非它们在 module map 中列出。为您的页面;相关模块引用必须以 ./../ 开头(以区别于对模块映射中列出的模块的引用)。

所以如果你不使用模块映射,这

import Yellow from "/src/yellow";

需要

import Yellow from "./yellow.js";

./因为index.jsyellow.js在同一个地方,相对路径是相对于模块执行导入 (index.js),而不是导入该模块的 HTML。


当您使用 type="module"(您必须这样做)时遇到的错误:

This lead to this Error:

Access to script at 'file:///D:/Game/src/index.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

大多数浏览器不允许您从 file:// URL 执行此操作,但 Firefox 允许。但是,即使在使用 Firefox 时,最好使用本地网络服务器进行 Web 开发,因为 许多 内容要么被阻止,要么与 file:// URL 和 的行为不同>http://https:// 网址。您的 IDE 中可能嵌入了一个,或者在本地安装 Apache 或 nginx 相当简单,或者您可以使用 Node.js 自行安装。和 ExpressKoa .

关于javascript - 导入类导致错误 : Uncaught syntaxerror unexpected identifier,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56826377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com