导入JS文件错误:无法在模块外部使用import语句

时间:2020-01-20 02:49:42

标签: javascript import module importerror

我已经多次问过这个问题。不幸的是,没有一种解决方案对我有用。

我正在尝试使用 import 导入JS文件。当我尝试这样做时,会出现以下错误:

"Uncaught SyntaxError: Cannot use import statement outside a module"

有人建议为我的html脚本标签分配类型模块。那不能解决我的问题。这样做时,我会收到以下错误

"Access to script at 'file:///C:/Users/James%20Mike%20Culhane/sites/JMike-C.github.io/simple-projects/class_tester/foodsname.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."

如果任何人都有导入文件的替代解决方案,我希望听到他们的声音。谢谢:)


我在下面包含了我的代码。首先是两个js文件,然后是html文件。就上下文而言,我正在尝试为打砖块游戏生成一个桨。

// index.js file

import {Paddle} from "./src/paddle"

let canvas = document.getElementById("gameScreen")

let ctx = canvas.getContext("2d")

const GAME_WIDTH = 800
const GAME_HEIGHT = 600

ctx.clearRect(0,0,800,600)

let paddle = new Paddle(GAME_WIDTH,GAME_HEIGHT)
paddle.draw(ctx)

// paddle.js file in src directory

export default class Paddle {
    constructor(gameWidth,gameHeight) {

        this.width = 150
        this.height = 30

        this.position = {
            x: gameWidth / 2 -this.width / 2,
            y: gameHeight - this.height - gameHeight/10
        }
    }
    draw(ctx) {
        ctx.fillRect(this.position.x,this.position.y,this.width,this.height)
    }
}
// index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <style>
            #gameScreen {
                border: 1px solid black;
            }
            img {
                display: none
            }
        </style>
    </head>
    <body>

        <center>
            <canvas id="gameScreen" width = 800 height = 600></canvas>
        </center>
        <script src="foodsname.js"></script>

    </body>
</html>

0 个答案:

没有答案