Javascript 在 Node.js 中包含来自外部文件的 es6 类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39005332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:06:38  来源:igfitidea点击:

Include es6 class from external file in Node.js

javascriptnode.js

提问by Bald Bantha

Say I have a file class.js:

说我有一个文件class.js

class myClass {
   constructor(arg){
      console.log(arg);
   }
}

And I wanted to use the myClassclass 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.exportsbut haven't found an example that works for es6 classes.

我想myClass在另一个文件中使用这个类。我该怎么办?
我试过:
var myClass = require('./class.js');
但是没有用。
我看过module.exports但还没有找到适用于 es6 类的示例。

回答by baao

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)

或使用新语法(可能需要您先对代码进行 babelify)

export class MyClass {
    constructor(arg){
        console.log(arg);
    }
};

and import with

并导入

import {myClass} from "./class.js";

回答by Abe Clark

export default class myClass {
   constructor(arg){
      console.log(arg);
   }
}

Other file:

其他文件:

import myClass from './myFile';