简体   繁体   English

如何导出ES6类并在另一个模块中构造它的实例?

[英]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.

相关问题 如何导出使用 NodeJS 中的 ES6 模块动态导入的 class 的实例? - How to export the instance of the class which is imported dynamically with ES6 module in NodeJS? 如何导出 es6 IIFE? - How do i export an es6 IIFE? 我应该/是否必须导出 Javascript ES6 中另一个导出的 class 返回的 class? - Should/do I have to export returning class returned by another exported class in Javascript ES6? 如何在不使用module.exports的情况下以JavaScript导出ES6类 - How to export ES6 class in Javascript without module.exports 如何执行与ES5和ES6兼容的导出? - How do I perform an export that is compatible with ES5 and ES6? 试图将类导出为模块ES6 babel - Trying to export a class as a module ES6 babel 如何在 Javascript 中检查脚本是否作为 ES6 模块运行(以便它可以“导出”)? - How do I check if a script is running as a ES6 module (so that it can `export`), in Javascript? 如何通过es6类构造数组 - How to Construct an array by es6 class 如何使用Javascript ES6 ES2015模块将常量直接导出/导入到导入模块名称空间? - How do I use Javascript ES6 ES2015 modules to export / import constants directly to the import module namespace? 如何在一个es6模块中创建类并在另一个模块中导入它? - How to create class in one es6 module and import it in another?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM