0

I currently have a hero.js file in a directory, and it looks like this

let Person = class PersonClass {
    constructor(name) {

        ...

class Hero {
    constructor(name, level) {

        ...

class Mage extends Hero {
    constructor(name, level, spell) {

        ...

Then in another file, I want to use these classes.

So I have:

require("./hero");

const manny = new Hero("Manny", 12);
const george = new Person("George");

and neither george nor manny work, they both throw Reference Error: Person/Hero is not defined.

When I have the Person or Hero class code in the file above george and manny, they do work properly.

I want to know how to move class definitions to another file and require them in another file.

Rentsy
  • 378
  • 3
  • 12
  • What environment: browser or something like node? In a browser you just need to make sure the hero script is included in the page before the other script, and the classes defined globally or some accessible scope. No need for require. – Patrick Evans Nov 20 '19 at 19:40
  • Try looking at different syntaxes (CommonJS vs ES6) - https://stackoverflow.com/questions/40294870/module-exports-vs-export-default-in-node-js-and-es6 – muka.gergely Nov 20 '19 at 19:47

1 Answers1

-1

It's very straightforward. you should use export

let Person = class PersonClass {
    constructor(name) {

        ...

class Hero {
    constructor(name, level) {

        ...

class Mage extends Hero {
    constructor(name, level, spell) {


export const Person
export const Hero
export const Mage

And in another file,

import {Person, Hero, Mage} from './hero'
Giorgi Lagidze
  • 773
  • 4
  • 24
  • Giorgi, I tried just dropping your suggestion in and ran into a problem ``` import {Person, Hero, Mage} from './hero' ^ SyntaxError: Unexpected token { ``` – Rentsy Nov 20 '19 at 20:27