24

Say I have a file class.js:

class myClass {
   constructor(arg){
      console.log(arg);
   }
}

And I wanted to use the myClass class in another file. How would I go about this?
I've tried:
var myClass = require('./class.js');
But it didn't work.
I've looked at module.exports but haven't found an example that works for es6 classes.

0

3 Answers 3

46

Either do

module.exports = class MyClass {
    constructor(arg){
        console.log(arg);
    }
};

and import with

var a = require("./class.js");
new a("fooBar");

or use the newish syntax (may require you to babelify your code first)

export class MyClass {
    constructor(arg){
        console.log(arg);
    }
};

and import with

import {myClass} from "./class.js";
1
  • 7
    I'm getting "Cannot use import statement outside a module" Oct 21, 2021 at 17:54
3
export default class myClass {
   constructor(arg){
      console.log(arg);
   }
}

Other file:

import myClass from './myFile';
2
  • This doesn't work for me. I suspect I have an outdated version of node. Aug 17, 2016 at 20:17
  • 2
    @BaldBantha this is because this is new ES6 syntax, you're going to need to use babel to transpile your ES6 to ES5 so node can run it. Node doesn't support import/export and never will (at least in the near future)
    – Downgoat
    Aug 18, 2016 at 1:12
1
export class MyClass
{
   constructor(arg){
    this.arg = arg;
}
}

import {MyClass} From'./MyClass.js'

class OtherClass{
 arg_two;

}

import {OtherClass} From'./OtherClass.js'

class1 = new OtherClass();
class1.arg_two.arg = 'class';

console.log(class1.arg_two.arg);
1
  • 6
    Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes
    – Boken
    Dec 4, 2020 at 0:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.