Javascript Module.exports 和 es6 导入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34278474/
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
Module.exports and es6 Import
提问by Nani
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.
与 babel 反应。我对导入和 module.exports 有这种困惑。我假设 babel 在将 ES6 代码转换为 ES5 时将导入和导出分别转换为 require 和 module.exports。
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.
如果我从一个模块导出一个函数并在另一个模块中导入该函数,则代码执行正常。但是,如果我使用 module.exports 导出函数并使用“import”导入,则会在运行时抛出错误,表示它不是函数。
I cooked up an example.
我编了一个例子。
// 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");
I used babel with preset es2015 to transcompile it. This gives me the following error
我使用带有预设 es2015 的 babel 来编译它。这给了我以下错误
Uncaught TypeError: (0 , _animals.Tiger) is not a function
Uncaught TypeError: (0 , _animals.Tiger) 不是函数
But if i remove the module.exports = Tiger;
And replace it with export { Tiger };
It works fine.
但是如果我删除它module.exports = Tiger;
并用它替换export { Tiger };
它工作正常。
What am i missing here??
我在这里错过了什么?
EDIT:I am using browserify as the module bundler.
编辑:我使用 browserify 作为模块捆绑器。
回答by Matt Molnar
export { Tiger }
would be equivalent to module.exports.Tiger = Tiger
.
export { Tiger }
将相当于module.exports.Tiger = Tiger
.
Conversely, module.exports = Tiger
would be equivalent to export default Tiger
.
相反,module.exports = Tiger
将等价于export default Tiger
。
So when you use module.exports = Tiger
and then attempt import { Tiger } from './animals'
you're effectively asking for Tiger.Tiger
.
因此,当您使用module.exports = Tiger
然后尝试时,import { Tiger } from './animals'
您实际上是在要求Tiger.Tiger
.
回答by jmarceli
If you would like to import:
如果您想导入:
module.exports = Tiger
you may use following construction:
您可以使用以下结构:
import * as Tiger from './animals'
Then it will work.
然后它会起作用。
Another option is changing the export as described by @Matt Molnar but it is only possible if you are the author of the imported code.
另一种选择是按照@Matt Molnar 的描述更改导出,但只有当您是导入代码的作者时才有可能。