why don’t have function by commonJS way?
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 ofmodule.exports
, soexports.add
actually ismodule.exports.add
, that is prop of Objectmodule.exports
. however calladd
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);