简体   繁体   中英

Include es6 class from external file in Node.js

Say I have a file class.js :

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

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

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)

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

and import with

import {myClass} from "./class.js";
export default class myClass {
   constructor(arg){
      console.log(arg);
   }
}

Other file:

import myClass from './myFile';
export class MyClass
{
   constructor(arg){
    this.arg = arg;
}
}

import {MyClass} From'./MyClass.js'

class OtherClass{
 arg_two;

}

import {OtherClass} From'./OtherClass.js'

class1 = new OtherClass();
class1.arg_two.arg = 'class';

console.log(class1.arg_two.arg);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM