导出和导入ECMA6类

时间:2017-03-20 15:33:06

标签: javascript node.js ecmascript-6

如何导出和使用ECMA6课程?这就是我现在正在做的事情:

parser.js

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

   static doNow() {
   }
}

现在在另一个文件中,我正在做:

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

parse上调用Parser时,我收到错误消息

SyntaxError: Unexpected identifier

突出显示Parser

这可能是什么原因?导出和导入类的正确性是什么?

3 个答案:

答案 0 :(得分:2)

您尝试以绝对方式调用模块,这是导致问题的原因。

我建议将IDE用作webstorm或atom,以便将来不会出现此类问题

试试这个:

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

是:

export default class Parser {
   static parse() {
   }

   static doNow() {
   }
}

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

答案 1 :(得分:2)

这样做更容易,更易读:

class Parser {
   static parse() {
   }

   static doNow() {
   }
}

module.exports = Parser;

并在要求模块中:

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

答案 2 :(得分:0)

我对此进行了测试,似乎问题是解析器的路径。

文件结构

-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() {
   }
}

<强>终端

node index.js 
parser hello there