【发布时间】:2012-08-24 13:21:01
【问题描述】:
我正在尝试为 Firefox 和 Chrome 编写跨浏览器扩展。 Firefox 使用 commonJS 规范,而 Chrome 只是像网页一样将所有内容集中到全局命名空间中。
为了能够编写可重用的代码,我正在尝试使用 requireJS 在 Chrome 扩展程序中加载代码,这样我就可以编写 commonJS 模块并让它们在两种环境中工作。
当我需要有条件地需要模块时,我遇到了问题。例如,Firefox 提供了对simple-storage 模块的访问,您应该使用它来访问本地存储。在 chrome 中,我需要使用他们提供的 localStorage API。所以,我一直在尝试这样做:
// storage.js
define(function(require, exports, module){
var store;
try {
// This module will only be available in the FF extension.
store = require('simple-storage').storage
} catch(error) {
// If it's not available, we must be in Chrome and we
// should use the localStorage object.
store = localStorage
}
// Use the store object down here.
});
但是这似乎不起作用。当我尝试加载 Chrome 扩展程序时,出现以下错误:
有没有更好的方法来 require 具有后备功能的模块?
【问题讨论】:
-
这里可能不完全相关,但无论 try 块是否抛出异常,都会运行“finally”。所以即使你的 try 块通过了,finally 块也会覆盖 store。那是你想要的吗?如果没有,我相信你所追求的就是 try/catch。
-
如果你的 try 块抛出错误,finally 块会被执行,然后错误被重新抛出
-
抱歉,我的意思是
catch。不管怎样,结果都是一样的。
标签: javascript requirejs commonjs js-amd