简体   繁体   English

如何执行与ES5和ES6兼容的导出?

[英]How do I perform an export that is compatible with ES5 and ES6?

I'm writing a "class" in node 我正在节点中写一个“类”

// mymodule/index.js

function MyClass() {}
MyClass.prototype.method1 = function() {..}

usually I do 通常我做

module.exports = MyClass

but I want my class available for both syntax 但我希望我的课程可用于两种语法

var MyClass = require('mymodule')

and

import {MyClass} from 'mymodule'

Which is the correct way to do it? 这是正确的方法吗?

As far as writing an export that is compatible for both ES5 and ES6, Babel already takes care of that for you. 对于编写兼容ES5和ES6的导出,Babel已经为您完成了这项工作。 (As communicated in the comments to your question. I'm only clarifying for those who got lost in the dialog.) (正如您对问题的评论中所述。我只是澄清那些在对话中迷路的人。)

module.exports = MyClass

will work with both var MyClass = require('mymodule') and import MyClass from 'mymodule 将使用var MyClass = require('mymodule')import MyClass from 'mymodule

However, to be clear, the actual syntax you asked about: 但是,要清楚,您询问的实际语法是:

import {MyClass} from 'mymodule'

means something different from 意味着不同的东西

import MyClass from 'mymodule'

For the latter, you would have to export it as: module.exports.MyClass = MyClass , and for ES5 modules it would have to required as var MyClass = require('mymodule').MyClass 对于后者,您必须将其导出为: module.exports.MyClass = MyClass ,对于ES5模块,必须将其作为var MyClass = require('mymodule').MyClass

Both ways are correct, but try to import in es6 like this without the brackets: 两种方式都是正确的,但尝试在没有括号的情况下导入es6这样:

import MyClass from 'mymodule'

Otherwise you would have to export your function like this: 否则你必须像这样导出你的函数:

module.exports.MyClass = MyClass

and than import it like this: 而不是像这样导入:

import { MyClass } from 'mymodule'

From the comments, I understand you are trying to run your ES6 frontend code in some mocha unit tests in node. 从评论中,我了解到您正在尝试在节点中的某些mocha单元测试中运行ES6前端代码。 Yes, you can't do that until node support ES6 modules. 是的,在节点支持ES6模块之前,您无法做到这一点。 If I were you, I would use systemjs to load code for those mocha tests. 如果我是你,我会使用systemjs为那些mocha测试加载代码。 Mocha supports promises, so it should be fairly painless to load any files before tests. Mocha支持promises,因此在测试之前加载任何文件应该相当轻松。

Writing syntax for both will just create more problems for you. 为两者编写语法只会为您创造更多问题。

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

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