【问题标题】:Importing classes causes Error: Uncaught syntaxerror unexpected identifier导入类导致错误:未捕获的语法错误意外标识符
【发布时间】:2023-03-20 12:38:01
【问题描述】:

我尝试将我的 Java 类 Yellow.js 导入我的 index.js 并获取

“未捕获的语法错误意外标识符”

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

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

进入

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

但这会导致:

从源“null”访问“file:///D:/Game/src/index.js”处的脚本 已被 CORS 策略阻止:跨源请求仅 支持协议方案: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>

index.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" 东西。

【问题讨论】:

  • 这导致此错误:CORS 策略已阻止从源“null”访问“file:///D:/Game/src/index.js”处的脚本:跨源请求仅支持协议方案:http、data、chrome、chrome-extension、https。

标签: javascript ecmascript-6 import module


【解决方案1】:

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

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

import Yellow from "/src/yellow";

需要

import Yellow from "./yellow.js";

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


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

这导致了这个错误:

CORS 策略已阻止从源“null”访问“file:///D:/Game/src/index.js”处的脚本:跨源请求仅支持协议方案:http、data、铬,铬扩展,https。

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

【讨论】:

  • 感谢您的回答。但它会导致与我使用 'type='module'' 相同的错误。
  • @RedDeadRabbit - 你必须使用type="module",你不能从文件系统 URL 中这样做。
  • 那么我做对了吗,我不能在本地机器上开发它?我需要设置服务器吗?
  • @RedDeadRabbit - 实际上,Firefox 允许您从file:// URL 加载模块(前提是页面位于file:// URL 上)。铬没有。不过,出于问题中列出的原因,我强烈建议使用 Web 服务器进程。
  • 我通过安装 node.js 并在 node.js 命令提示符下运行和 http-server 解决了这个问题。效果很好。谢谢支持!
猜你喜欢
  • 2015-06-15
  • 1970-01-01
  • 2020-06-20
  • 2021-12-16
  • 2013-11-28
  • 1970-01-01
  • 2013-11-28
相关资源
最近更新 更多