admin管理员组

文章数量:1293213

Using Node.js version 7.7.2, I'd like to define and export an ES6 class from a module like this:

// Foo.js
class Foo {
    construct() {
        this.bar = 'bar';
    }
}
module.exports = Foo;

And then import the class into another module and construct an instance of said class like this:

// Bar.js
require('./foo');
var foo = new Foo();
var fooBar = foo.bar;

However, this syntax does not work. Is what I am trying to do possible, and if so, what is the correct syntax to achieve this?

Thanks.

Using Node.js version 7.7.2, I'd like to define and export an ES6 class from a module like this:

// Foo.js
class Foo {
    construct() {
        this.bar = 'bar';
    }
}
module.exports = Foo;

And then import the class into another module and construct an instance of said class like this:

// Bar.js
require('./foo');
var foo = new Foo();
var fooBar = foo.bar;

However, this syntax does not work. Is what I am trying to do possible, and if so, what is the correct syntax to achieve this?

Thanks.

Share edited Apr 25, 2017 at 23:19 Allen More asked Apr 25, 2017 at 21:07 Allen MoreAllen More 9083 gold badges16 silver badges25 bronze badges 3
  • Do you know how do use modules in pre-ES6 nodejs? – Bergi Commented Apr 25, 2017 at 21:21
  • The obvious problem here is that you set the property foo but look for the property bar... – lonesomeday Commented Apr 25, 2017 at 21:47
  • Yup, that was a typo. Just fixed it. Good catch. Status Report: Currently working on an implementation of this, will be back soon with results. – Allen More Commented Apr 25, 2017 at 22:01
Add a ment  | 

2 Answers 2

Reset to default 8

You have to use regular node module syntax for this.

You have a few mistakes in your sample code. First, the class should not be followed by (). Also, a class constructor should be constructor not construct. Look at the below foo.js for proper syntax.

foo.js

class Foo {
  constructor () {
    this.foo = 'bar';
  }
}

module.exports = Foo;

bar.js

const Foo = require('./foo');

const foo = new Foo();

console.log(foo.foo); // => bar
// Foo.js
export class Foo() {
    construct() {
        this.foo = 'bar';
    }
}

notice keyword EXPORT

本文标签: javascriptHow do I export an ES6 class and construct an instance of it in another moduleStack Overflow