Browserify:如果需要,使用module.exports,否则暴露全局 [英] Browserify: Use module.exports if required, otherwise expose global

查看:275
本文介绍了Browserify:如果需要,使用module.exports,否则暴露全局的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑为我的某些项目采用 browserify ,但我希望确保其他项目不如果要使用(捆绑的)代码,必须使用browserify。显而易见的方法是通过 module.exports 以及通过窗口公开模块导出。全球。但是,我宁愿不为那些 require 脚本的人污染全局命名空间。

I'm considering adopting browserify for some of my projects, but would like to make sure that others don't have to use browserify if they want to use the (bundled) code. The obvious way to do this is to both expose the modules exports through module.exports as well as through a window. global. However, I'd rather not pollute the global namespace for those who are requireing the script.

是吗可以检测脚本是否 require d?如果是,那么我可以这样做:

Is it possible to detect if a script is being required? If it is, then I could do something like:

var mymodule = (function() { ... })();
if (isRequired()) {
  module.exports = mymodule;
} else {
  window.mymodule = mymodule;
}

请注意,无论如何,这都将预先捆绑,所以 var mymodule 不会暴露全局。此外,目前我正在使用揭示模块模式,但是愿意切换到更适合浏览器化的东西。

Note that no matter what, this will be bundled beforehand, so the var mymodule won't be exposing a global. Also, currently I'm using the revealing module pattern, but would be willing to switch to something more appropriate for browserify.

制作模块的最佳方法是什么要求能够和< script src = 能够吗?在两种情况下暴露全局是否最好?

What's the best way to make a module both requireable and <script src=able? Is it best to just expose a global in both circumstances?

推荐答案

Forbes Lindesay有一篇很好的文章解释了如何独立完成版本:
http://www.forbeslindesay.co.uk/post/46324645400/ standalone-browserify-builds

There is a good article from Forbes Lindesay explaining how to do standalone builds: http://www.forbeslindesay.co.uk/post/46324645400/standalone-browserify-builds

短版本,使用独立选项:

The short version, use the standalone option:

browserify beep.js --standalone beep-boop > bundle.js

这篇关于Browserify:如果需要,使用module.exports,否则暴露全局的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆