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 propertybar
... – 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
2 Answers
Reset to default 8You 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
版权声明:本文标题:javascript - How do I export an ES6 class and construct an instance of it in another module? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741572074a2386069.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论