我有一个Node.js脚本所需的脚本,我想保持JavaScript引擎独立。
例如,我只想exports.x = y;
在Node.js下运行。如何执行此测试?
发布此问题时,我不知道Node.js模块功能是否基于CommonJS。
对于我给出的具体示例,一个更准确的问题是:
脚本如何判断是否已将其作为CommonJS模块使用?
通过寻求CommonJS支持,这是Underscore.js库的实现方式:
编辑:对您的更新问题:
(function () {
// Establish the root object, `window` in the browser, or `global` on the server.
var root = this;
// Create a reference to this
var _ = new Object();
var isNode = false;
// Export the Underscore object for **CommonJS**, with backwards-compatibility
// for the old `require()` API. If we're not in CommonJS, add `_` to the
// global object.
if (typeof module !== 'undefined' && module.exports) {
module.exports = _;
root._ = _;
isNode = true;
} else {
root._ = _;
}
})();
这里的示例保留了Module模式。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句