Javascript 从duo Build js访问脚本中的对象
我正在使用duo.js,但希望公开一个对象,以便可以在html文件的其他部分中访问它 在我的index.js文件中,我有Javascript 从duo Build js访问脚本中的对象,javascript,duo.js,Javascript,Duo.js,我正在使用duo.js,但希望公开一个对象,以便可以在html文件的其他部分中访问它 在我的index.js文件中,我有 var uuid = require('gjohnson/uuid'); var bind = require('ianstormtaylor/bind'); function User(options){ this.protocol = window.location.protocol; this.options(options); } User.prototype
var uuid = require('gjohnson/uuid');
var bind = require('ianstormtaylor/bind');
function User(options){
this.protocol = window.location.protocol;
this.options(options);
}
User.prototype.randomID = function(){
return uuid();
};
module.exports = bind.all(new User());
var user = module.exports.User = User;
我运行duo index.js
来创建build/index.js
文件
然后,我希望能够访问index.html中脚本中的user
对象:
<script type="text/javascript" src="build/index.js"></script>
<script>
(function() {
console.log(user.randomID());
})();
</script>
(功能(){
console.log(user.randomID());
})();
但我得到了“ReferenceError:用户未定义”。我仍在学习duo,不熟悉它的结构。如何正确地公开用户对象以便可以访问它?Duo不会将它构建的脚本公开到全局上下文中。因此,您不使用内联脚本,而是使用Duo构建脚本并在外部提供服务 当前作为
index.js
的脚本可能类似于lib/user.js
。然后,真正的index.js
应该放在页面逻辑的位置,比如user.randomID()代码>
如果要使开发过程更容易,请考虑使用一个工具,它可以在每次刷新时自动重建脚本。
要将生成的模块公开给窗口
对象,请使用--global
CLI标志。如果您需要以其他软件包管理器更易使用的方式公开模块,请使用--standalone
,它将使用UMD输出您的脚本。谢谢@dominic barnes。我已经准备好通过Segment.io/analytics.js了解Duo的很多实现。他们是如何公开分析
对象的?Duo确实有--global
CLI标志,您可以将正在构建的模块导出为全局值。(参见)顺便说一句,是segmentio/analytics.js的Makefile
。他们使用的是--standalone
标志,该标志通过UMD导出库。(因此其他包管理器可以使用它)但是如果您只需要导出到全局范围,您可以使用--global
。这正是我想要的。如果你更新你的回复,我会把它标记为答案:)谢谢