Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include es6 class from external file in Node.js

Tags:

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.

like image 275
Bald Bantha Avatar asked Aug 17 '16 20:08

Bald Bantha


People also ask

Does node support ES6 classes?

Finally es6 classes have landed in Node.

Can I use ES6 import in node?

The syntax for importing modules in ES6 looks like this. The reason for this error is that Node js doesn't support ES6 import directly. If you try to use import for importing modules directly in node js it will throw out that error.


1 Answers

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"; 
like image 191
baao Avatar answered Oct 31 '22 16:10

baao