如何执行与ES5和ES6兼容的导出? [英] How do I perform an export that is compatible with ES5 and ES6?

查看:99
本文介绍了如何执行与ES5和ES6兼容的导出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在节点中写一个类

// mymodule/index.js

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

通常我做

module.exports = MyClass

但我希望我的课程可用于两种语法

but I want my class available for both syntax

var MyClass = require('mymodule')

import {MyClass} from 'mymodule'

这是正确的方法吗?

推荐答案

至于编写兼容ES5和ES6的导出,Babel已经采用照顾你。 (正如你在问题的评论中所说的那样。我只是澄清那些在对话中迷路的人。)

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.)

module.exports = MyClass

将同时使用 var MyClass = require('mymodule ')从'mymodule 中导入MyClass

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

但是,要清楚,您询问的实际语法:

However, to be clear, the actual syntax you asked about:

import {MyClass} from 'mymodule'

表示不同于

import MyClass from 'mymodule'

对于后者,您必须将其导出为:模块。 exports.MyClass = MyClass ,对于ES5模块,它必须为 var MyClass = require('mymodule')。MyClass

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

这篇关于如何执行与ES5和ES6兼容的导出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆