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";
Sign up to request clarification or add additional context in comments.

1 Comment

I'm getting "Cannot use import statement outside a module"
3
export default class myClass {
   constructor(arg){
      console.log(arg);
   }
}

Other file:

import myClass from './myFile';

2 Comments

This doesn't work for me. I suspect I have an outdated version of node.
@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)
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 Comment

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

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.