Import and Export JS

1

Before anything a taste, my name is Brian and I am from Argentina. It's the first time I ask on this site, I really did not know him and he seems to be very good haha.

I tell you ... I have a small project of a game in JS that is based on turn-based combat against an AI that I am programming.

Now, I need to bring from a file called "clases.js" just the classes like my AI and my player, each with their main statistics.

export class humano {       
  constructor() {
    this.hp = 500
    this.hpv = this.hp
    this.atk = 13   }

  atacar(who){
    who.hpv=who.hpv - this.atk  } };

Now to that class I want to call it from my 'index.js' which is the main file where I do all the actions.

import humano from 'clases.js';
let jorge = new humano;
console.log(jorge);

I want to believe that this is how a class is imported or what is not from another file?

The error that the Chrome console gives me is:

  

Uncaught SyntaxError: Unexpected token export

I hope you can give me a hand, the idea with this project is to be able to learn Javascript better, I am relatively new in what is programming but I am practicing every day feeling more fluent, but if I do not ask I do not advance :) thank you very much and I hope you have formulated the question well.

Edit! Maybe I should use Babel ... I do not understand it well .. you will say.

    
asked by Alfacoy 08.06.2017 в 02:02
source

1 answer

1

You need to add default, export default class Human if you use es2016

or simply:

class Human {

}

module.exports = Human;

// or
export default Human;

this is why you can export in different ways

// Export
var obj = {};
var myVariable = 0;
module.exports.obj = obj;
module.exports.myVariable = myVariable;

export const obj = {};
export const myVariable = {};

// import
const { obj, myVariable } = require('./human');
const { obj, myVariable } from './human';

you do not need to add the .js extension, there is a file search hierarchy where you first look for the .js extension after .json

Note: If you are going to use classes ocupas use babel, chrome already supports several features of es6 but the classes are not yet, and other things JavaScript Destructuring assignment = > import {} from; that has not yet reached version 7 of node, is a feature that will take a while to arrive maybe next year, so I recommend you use babel if you want to work with these features, greetings!

    
answered by 08.06.2017 / 03:58
source