如何导入和导出Javascript ES6类

3

我是JavaScript和Node.js的新手,我正在使用这个项目来发展我的技能并学习新技术。目前,我的项目使用多个相互依赖的类。这些类文件存储在不同的目录中,我正在尝试使用export和require语句来允许其他文件引用这些类。我还使用browserify和watchify将所有文件打包在一起,以简化HTML脚本标签。

以下是项目布局(JavaScript文件夹):

-Base (Folder)
 --Game.js (Class)
 --Player.js (Class)
 --Ball.js (Class)
-Helpers (Folder)
 --Draw.js (Class)
 --Helper.js (Class) 
-GameType (Folder)
 --Game1.js (Class)

相互依赖的类如下所示。
Game is Dependent on 
--Draw.js
--Helper.js
Player and Ball are Dependent on 
--Helper.js
Game1
--Game.js
--Ball.js
--Player.js

该项目在app.js文件中加载,并需要game1文件。目前,我正在尝试测试并使所有的require和export语句正常工作。目前,在app.js文件中,我可以创建一个game1对象,但是我无法访问其中的变量和方法。我可以使用console.log输出对象,并且它具有所有正确的变量和方法,因此它正确地创建了game1对象,但我无法访问任何部分。我不确定我当前是否正确使用ES6类符号的require和export语句,或者我的代码是否存在其他问题。请问我是否正确使用require和export语句?
以下是类和app.js文件的片段。一些类中的方法需要完成,但我正在尝试添加require和export功能以使我的代码导航更好。希望您能帮助我找到解决问题的方法。
app.js
const Game1 = require('./GameType/game1.js');

window.onload = function(){
    console.log("Test Started");

    console.log();

    var canvasLocator = document.querySelector("#gameCanvas");
    var canvasContext = canvasLocator.getContext("2d");

    var game1 = new Game1();

    //Prints out the correct object in the console
    console.log(game1);

    game1.draw();
    //Returns an empty array of objects
    //In my test is should return a draw obj 
}

Game1.js

const Game = require('../Base/Game.js');
const Ball = require('../Base/Ball.js');
const Player = require('../Base/Player.js');

class Game1 extends Game{
    constructor(){
        super();
        this.ball = new Ball(400, 300);
        this.player1 = new Player("User", 15, 275, "blue");
        this.player2 = new Player("AI", 775, 275, "blue");
        this.mouseYPos;
    }

    refresh(){
        //Needs to be implemented
    }


    draw(){
        console.log("Super Draw: " + this.ball);
    }


    moveEverything(){
        //Needs to be implemented
    }
}

module.exports = Pong;

Game.js作为一个接口,也具有所有游戏所必需的变量。

'use strict';

const Helper = require('../Helpers/Helper.js');
const Draw = require('../Helpers/Draw.js');

class Game{
    constructor(){
        this.interval;
        this.started = false;
        this.framesPerSecond = 30;
        this.drawObj = new Draw();
        this.helper = new Helper();
    }

    //Each game needs to implement 
    draw(){
        console.log("draw() not implemented in child class!");
    }

    moveEverything(){
        console.log("moveEverything() not implemented in child class!");
    }

    refresh(){
        console.log("refresh() not implemented in child class!");
    }
};

module.exports = Game

Ball

const Helper = require('../Helpers/Helper.js')

class Ball{
    constructor(x, y){
        this.ballX = x;
        this.ballY = y;
        this.ballSpeedX;
        this.ballSpeedY;
        this.ballSpeedXChange;
        this.ballSpeedYChange;
        this.helper = new Helper();
    }

    move(x,y){
        this.ballX = this.ballX + x;
        this.ballY = this.ballY + y;
    }

    increaseSpeed(speedX, speedY){
        this.ballSpeedX = this.ballSpeedX + speedX;
        this.ballSpeedY = this.ballSpeedY + speedY;
    }

    reflectBall(player, drawObj){

    }

    reflect(ptOfContact, paddleSpeed){

    }

    setBallDifficulty(difficulty){
        switch(difficulty){
            case "Easy":
                this.ballSpeedXChange = -1;
                this.ballSpeedYChange = 1;
                break;
            case "Medium":
                this.ballSpeedXChange = -1.5;
                this.ballSpeedYChange = 1.5;
                break;    
            case "Hard":
                this.ballSpeedXChange = -2;
                this.ballSpeedYChange = 2;
                break;
            default:
                console.log("No difficulty Found");
        }
    }
}

module.exports = Ball

播放器

const Helper = require('../Helpers/Helper.js');

class Player{
    constructor(input, x, y, color){
        //Boolean value for AI or Actual Player
        this.inputType = this.inputType(input);
        this.playerX = x;
        this.playerY = y;
        this.playerSpeed;
        this.playerScore = 0;
        this.paddleWidth = 10;
        this.paddleHeight = 50;
        this.color = color;
        this.helper = new Helper();
    }

    move(drawObj){
        //True: User Input
        //False: AI Input 
        if(this.inputType){
            this.movePlayerInYDir(drawObj);
        }
        else{
            this.movePlayerAIInYDir(drawObj);
        }
    }

    movePlayerInYDir(drawObj){
        let before = this.playerY;
        this.playerY = this.helper.playerInput(drawObj);
        this.playerSpeed = this.playerY - before;
        if((this.playerY + this.paddleHeight) >= (drawObj.getBaseHeight())){
            this.playerY = (drawObj.getBaseHeight() - this.paddleHeight);
        }
    }

    movePlayerAIInYDir(drawObj){
        this.playerSpeed = this.setBotDifficulty("Easy");
        this.playerY = this.playerY + this.playerSpeed;
        if(this.playe2Y <= 0){
            //Hits Top 
            this.playerSpeed = (this.playerSpeed) * -1; 
        }
        else if((this.playerY + this.paddleHeight) >= drawObj.getBaseHeight()){
            //Hits Bottom
            this.playerSpeed = (this.playerSpeed) * -1;
        }
    }

    setAIDifficulty(difficulty){
        switch(difficulty){
            case "Easy":
                //TODO
                break;
            case "Medium":
                //TODO 
                break;
            case "Hard":
                //TODO
                break;
            case "Practice":
                //Unbeatable Mode
                break;
            default:
                console.log("No difficulty Found");
        }
    }

    //Helper
    inputType(type){
        //True: Real Input 
        //False: AI
        switch(type){
            case "User":
                return true;
            case "AI":
                return false;
            default:
                console.log("Type not recognized");
        }
    }

}

module.exports = Player

Helper

class Helper{
    constructor(){
        this.gameType;
        this.canvasLocator = document.querySelector("#gameCanvas");
        this.canvasContext = this.canvasLocator.getContext("2d");
        this.mouseXPos;
        this.mouseYPos;
    }

    getMouseYPos(canvas, evt) {
        var rect = canvas.getBoundingClientRect();
        return (evt.clientY - rect.top);

    }

    playerInput(drawObj){
        let c = this.canvasLocator;
        let helper = this;
        //let game = this;
        //let mouseYPos;
        //console.log(game);
        c.addEventListener("mousemove", function(evt){  
                                            helper.mouseYPos = helper.getMouseYPos(c, evt);                                
                                        } 
                                      , false);  
        //console.log(game.mouseYPos); 
        return helper.mouseYPos;     
    }

    change(speed){
        //Ball Function for reflection 
        if(speed > 8 || speed < -8){
            return 2;
        }
        return (Math.abs(1/8 * speed) + 1);
    }

    randomIntNumber(min, max){
        min = Math.ceil(min);
        max = Math.floor(max);
        return Math.floor(Math.random() * (max - min)) + min;
    }

    randomSpeed(){
        if(this.randomIntNumber(0, 100) % 2 == 0){
            return this.randomIntNumber(-7, -9);
        }
        else{
            return this.randomIntNumber(7, 9);
        }
    }

    randomNumber(min, max){
        return (Math.random() * (max - min)) + min;
    }
}

module.exports = Helper

感谢您的帮助。
1个回答

3

首先,您问如何在ES6中导入和导出。在回答这个问题之前,需要注意的是,ES6模块语法与Node.JS导入模块的方式不同。您的示例正在使用Node.JS Common.js样式模块加载。

在ES6中,您可以这样导入模块...

import jquery from 'jquery';

如果你正在加载 node_modules 文件夹之外的内容...
import myClass from './path/to/where/the/file/is';

我刚刚提供的两个示例是如何将整个文件作为依赖项加载。

现在,如果您只想导入单个函数以供使用,也可以使用ES6。

test.js

const myFunction = () => { alert("hello world") };
export { myFunction }

现在你可以这样导入只有 myFunction 的函数...
import { myFunction } from './path/to/test.js';

需要注意的是,目前原生浏览器还无法导入JavaScript模块。因此,我们需要使用类似于Webpack这样的工具来提供使用ES6导入和导出模块的能力。

https://webpack.github.io/


使用Browserify和Webpack的最大区别是什么?目前我正在使用Browserify来捆绑我的模块,这可能是问题的原因吗?Webpack更容易实现吗? - Will Udstrand
1
我会说Browserify更容易,但实际上也可以使用<script type="module" src="car.js">标签加载所有模块!与打包不同,您将单独加载所有.js文件。 - Kokodoko

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接