Javascript 如何执行与 ES5 和 ES6 兼容的导出?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30241729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I perform an export that is compatible with ES5 and ES6?
提问by rkmax
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?
哪个是正确的方法?
回答by Lioness
As far as writing an export that is compatible for both ES5 and ES6, Babel already takes care of that for you. (As communicated in the comments to your question. I'm only clarifying for those who got lost in the dialog.)
至于编写兼容 ES5 和 ES6 的导出,Babel 已经为您处理好了。(正如在对您的问题的评论中所传达的那样。我只是为那些在对话中迷路的人澄清。)
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
回答by Arwed Mett
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'
回答by Capaj
From the comments, I understand you are trying to run your ES6 frontend code in some mocha unit tests in node. Yes, you can't do that until node support ES6 modules. If I were you, I would use systemjsto load code for those mocha tests. Mocha supports promises, so it should be fairly painless to load any files before tests.
从评论中,我了解到您正在尝试在 node.js 中的某些 mocha 单元测试中运行 ES6 前端代码。是的,在 node 支持 ES6 模块之前你不能这样做。如果我是你,我会使用systemjs来加载那些 mocha 测试的代码。Mocha 支持 promise,因此在测试之前加载任何文件应该是相当轻松的。
Writing syntax for both will just create more problems for you.
为两者编写语法只会给您带来更多问题。

