Suhail Gupta
Suhail Gupta

Reputation: 23216

Export and import the ECMA6 class

How to export and use the ECMA6 class? This is what I am doing now:

parser.js

module.exports = class Parser {
   static parse() {
   }

   static doNow() {
   }
}

Now in another file, I am doing:

var Parser = require('parser')
Parser.parse();

When parse is called on Parser, I get an error saying

SyntaxError: Unexpected identifier

with Parser highlighted.

What could be the reason for this? What is the correct to export and import the class?

Upvotes: 2

Views: 1535

Answers (3)

Hajji Tarik
Hajji Tarik

Reputation: 1082

You try to call your module in an absolute way this is what causes problem.

I recommend using an IDE as webstorm or atom to not have this kind of problem in the future

try this :

var Parser = require('path/path/parser.js');
    Parser.parse();

for es6 is :

export default class Parser {
   static parse() {
   }

   static doNow() {
   }
}

import Parser from './path/path/parser';

Upvotes: 2

rsp
rsp

Reputation: 111316

It's easier and more readable to do it like this:

class Parser {
   static parse() {
   }

   static doNow() {
   }
}

module.exports = Parser;

and in the requiring module:

const Parser = require('./path/to/module');
Parser.doNow();
// etc.

Upvotes: 2

Michael Warner
Michael Warner

Reputation: 4217

I tested this and it seems the issue is the path of parser.

File Structor

-index.js

-parser.js

index.js

var Parser = require('./parser')
console.log('parser',Parser.parse());

parser.js

module.exports = class Parser {
   static parse() {
       return 'hello there'
   }

   static doNow() {
   }
}

Terminal

node index.js 
parser hello there

Upvotes: 0

Related Questions