Module.exports和es6 Import [英] Module.exports and es6 Import

查看:619
本文介绍了Module.exports和es6 Import的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与通天塔反应.我对import和module.exports感到困惑.我假设babel在将ES6代码转换为ES5时分别将导入和导出分别转换为require和module.exports.

React with babel. I have this confusion with imports and module.exports. I assume babel when converting the ES6 code to ES5 converts the imports and exports to require and module.exports respectively.

如果我从一个模块中导出功能,然后在另一个模块中导入功能,则代码可以正常执行.但是,如果我使用module.exports导出函数并使用"import"导入,则在运行时会抛出错误,指出它不是函数.

If i export a function from one module and import the function in another module, the code executes fine. But if i export the function with module.exports and import using "import" the error is thrown at runtime saying it is not a function.

我做了一个例子.

// Tiger.js
function Tiger() {
    function roar(terrian){
        console.log('Hey i am in ' +  terrian + ' and i am roaing');
    };
    return roar;
}

module.exports = Tiger;

// animal.js
import { Tiger } from './animals';

var animal = Tiger();
animal("jungle");

我使用带有预设es2015的babel对其进行编译.这给了我以下错误

I used babel with preset es2015 to transcompile it. This gives me the following error

未捕获的TypeError:(0,_animals.Tiger)不是函数

但是,如果我删除了module.exports = Tiger;并用export { Tiger };替换了它,效果很好.

But if i remove the module.exports = Tiger; And replace it with export { Tiger }; It works fine.

我在这里想念什么?

我正在使用browserify作为模块捆绑器.

I am using browserify as the module bundler.

推荐答案

export { Tiger }等同于module.exports.Tiger = Tiger.

相反,module.exports = Tiger等同于export default Tiger.

因此,当您使用module.exports = Tiger并尝试import { Tiger } from './animals'时,实际上是在要求Tiger.Tiger.

So when you use module.exports = Tiger and then attempt import { Tiger } from './animals' you're effectively asking for Tiger.Tiger.

这篇关于Module.exports和es6 Import的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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