简体   繁体   English

导出和导入ECMA6类

[英]Export and import the ECMA6 class

How to export and use the ECMA6 class? 如何导出和使用ECMA6类? This is what I am doing now: 这就是我现在正在做的:

parser.js 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 Parser上调用parse ,出现错误提示

SyntaxError: Unexpected identifier

with Parser highlighted. 突出显示Parser

What could be the reason for this? 这可能是什么原因? What is the correct to export and import the class? 导出和导入类的正确方法是什么?

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 我建议将IDE用作网络风暴或原子,以免将来出现此类问题

try this : 尝试这个 :

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

for es6 is : 对于es6是:

export default class Parser {
   static parse() {
   }

   static doNow() {
   }
}

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

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.

I tested this and it seems the issue is the path of parser. 我对此进行了测试,看来问题出在解析器的路径上。

File Structor 文件结构

-index.js -index.js

-parser.js -parser.js

index.js index.js

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

parser.js parser.js

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

   static doNow() {
   }
}

Terminal 终奌站

node index.js 
parser hello there

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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