Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

javascript - Module.exports and es6 Import

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.

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.

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

Uncaught TypeError: (0 , _animals.Tiger) is not a function

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

What am i missing here??

EDIT: I am using browserify as the module bundler.

question from:https://stackoverflow.com/questions/34278474/module-exports-and-es6-import

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

export { Tiger } would be equivalent to module.exports.Tiger = Tiger.

Conversely, module.exports = Tiger would be equivalent to export default Tiger.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...