why don’t have function by commonJS way?

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ccaoee/article/details/82252506

why don’t have function by commonJS way?, have below code:

exports.add = function(a, b) {
    return a + b
}
add(2, 3) //-> ReferenceError: add is not defined

wake up, i understand the origin of problem. exports is shorthand of module.exports, so exports.add actually is module.exports.add, that is prop of Object module.exports. however call add function is a prop of global object actually.
so got a error: ReferenceError: add is not defined. use es6 export should no the problem. below code:

export const add = function(a, b) {
    return a + b
}
add(2, 3) //-> 5

// babel complier to es5

"use strict";

Object.defineProperty(exports, "__esModule", {
    value: true
});
var add = exports.add = function add(a, b) {
    return a + b;
};
add(2, 3);

so we write such code that is no problem if we want don’t to use grammar of es6:

var add = exports.add = function add(a, b) {
    return a + b;
};
add(2, 3);

猜你喜欢

转载自blog.csdn.net/ccaoee/article/details/82252506