javascript module.exports 客户端
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12571737/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
module.exports client side
提问by Parris
I've created a node module that is essentially just some useful JS that can also be used client side. I know that require.js can load common.js components, but I don't necessarily want to make a mandate that everyone who uses my module client side also needs require or common.js or something. I also don't want to force them to remove the module.exports = ...
at the bottom of the file. How do others solve this problem? Do you just create 2 versions, or 2 "compiled" versions rather? Does module.exports work everywhere?
我创建了一个节点模块,它本质上只是一些有用的 JS,也可以在客户端使用。我知道 require.js 可以加载 common.js 组件,但我并不一定要强制要求每个使用我的模块客户端的人也需要 require 或 common.js 之类的东西。我也不想强迫他们删除module.exports = ...
文件底部的 。其他人是如何解决这个问题的?你只是创建 2 个版本,还是 2 个“编译”版本?module.exports 是否无处不在?
采纳答案by Jonathan Ong
This is what underscore.js does:
这就是 underscore.js 所做的:
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root['_'] = _;
}
回答by frodeborli
I find this simpler:
我觉得这更简单:
try {
module.exports = exports = MyModule;
} catch (e) {}
This file can be included in both the browser and node.js.
该文件可以包含在浏览器和 node.js 中。
回答by Casey Foster
This has worked for me (CoffeeScript). Assume 'Namespace' is what you want to claim on the window
scope for the client
这对我有用(CoffeeScript)。假设“命名空间”是您要window
为客户端声明的范围
(module ? {}).exports = @Namespace =
my: 'cool'
module: '!'
Then you can use require('namespace').my === 'cool'
in Node.js or Namespace.my === 'cool'
in the browser. This translates into JS as
然后你可以require('namespace').my === 'cool'
在 Node.js 或Namespace.my === 'cool'
浏览器中使用。这转化为 JS 为
(typeof module !== "undefined" && module !== null ? module : {}).exports = this.Namespace = {
my: 'cool',
module: '!'
};