[英]How do I export an ES6 class and construct an instance of it in another module?
Using Node.js version 7.7.2, I'd like to define and export an ES6 class from a module like this: 使用Node.js版本7.7.2,我想从这样的模块定义和导出ES6类:
// 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. 谢谢。
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 ()
. 首先,
class
不应该跟()
。 Also, a class constructor should be constructor
not construct
. 此外,类构造函数应该是
constructor
而不是construct
。 Look at the below foo.js
for proper syntax. 请查看下面的
foo.js
以获得正确的语法。
foo.js foo.js
class Foo {
constructor () {
this.foo = 'bar';
}
}
module.exports = Foo;
bar.js 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 通知关键字EXPORT
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.