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.
exportsis shorthand ofmodule.exports, soexports.addactually ismodule.exports.add, that is prop of Objectmodule.exports. however calladdfunction 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);

博客探讨了CommonJS方式找不到函数的问题。分析发现代码中存在误解,相关调用实际是对象属性,而调用函数是全局对象属性,会导致错误。还指出使用ES6 export可解决该问题,也给出不使用ES6语法的可行代码。
1万+

被折叠的 条评论
为什么被折叠?



