我需要一个 node 的脚本.js脚本,我想保持JavaScript引擎独立.
例如,我只想在 node 下运行exports.x = y;
次.js.我怎样做这个测试?
在发布这个问题时,我不知道 node .js模块功能基于CommonJS.
对于我给出的具体例子,一个更准确的问题是:
脚本如何判断它是否是CommonJS模块所必需的?
我需要一个 node 的脚本.js脚本,我想保持JavaScript引擎独立.
例如,我只想在 node 下运行exports.x = y;
次.js.我怎样做这个测试?
在发布这个问题时,我不知道 node .js模块功能基于CommonJS.
对于我给出的具体例子,一个更准确的问题是:
脚本如何判断它是否是CommonJS模块所必需的?
By looking for CommonJS support,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._ = _;
}
})();
这里的示例保留了模块模式.