天地之灵

pomelo实战填坑记 前端坑之Buffer is not defined

实战pomelo过程中,自己重新进行component build之后发现输出的网页在浏览器端报错:

Uncaught ReferenceError: Buffer is not defined

阅读代码后分析如下:
模块 pomelo-protocol 的代码,试图兼容node.js与浏览器端,其区分方法是 判断module是否是一个object。
('object' === typeof module ? module.exports : (this.Protocol = {}),'object' === typeof module ? Buffer : Uint8Array, this);

在node.js中,module是一个object,而在浏览器端,早期版本的component实现 把module的函数自身作为最后一个参数(命名为module)
  if (!module.exports) {
    module.exports = {};
    module.client = module.component = true;
    module.call(this, module.exports, require.relative(resolved), module);
  }

所以typeof(module)得到的是一个function。

但是随着component的更新,component改变了这个特性:
  if (!module._resolving && !module.exports) {
    var mod = {};
    mod.exports = {};
    mod.client = mod.component = true;
    module._resolving = true;
    module.call(this, mod.exports, require.relative(resolved), mod);
    delete module._resolving;
    module.exports = mod.exports;
  }

可以看到最后一个参数现在是一个新创建出来的Object,所以现在在浏览器上,pomelo-protocol也认为现在正在node.js环境中,于是就报错了。

一个临时的workaround办法是,在require("promelo-protocol")之前,先准备好Buffer,代码如下:

window.Buffer = Uint8Array;
var protocol = require('pomelo-protocol');
window.Protocol = protocol;
delete window.Buffer;
这样问题暂时消除了。当然,最靠谱的办法还是在pomelo-protocol中修改识别环境的办法。稍后我会向pomelo提交pull-request帮助解决这一问题。

posted on 2013-11-10 11:17 天地之灵 阅读(7736) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2013年11月>
272829303112
3456789
10111213141516
17181920212223
24252627282930
1234567

导航

统计

常用链接

留言簿(3)

随笔档案

文章档案

搜索

最新评论

阅读排行榜

评论排行榜