【问题标题】:Conditionally require code in commonJS AMD module有条件地要求 commonJS AMD 模块中的代码
【发布时间】: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


【解决方案1】:

这里有两个警告:

1) 检测 chrome 是否正在运行

// detects webKit (chrome, safari, etc..)
var isChrome = 'webKitTransform' in document.documentElement.style

2) Requirejs 将解析define() 函数并搜索require('module') 调用。为了防止 chrome 上的错误,您以某种方式编写了 require,当 requirejs 解析函数体时,它不会将调用识别为模块依赖项:

if (isChrome)
   // use localStorage
else {
   // set the module name in a var does the trick,
   // so requirejs will not try to load this module on chrome.
   var ffStorageModule = 'simple-storage';
   return require(ffStorageModule);
}

【讨论】:

  • 模块 'simple-storage' 需要预先加载,否则会出现类似错误:Uncaught Error: Module name "simple-storage" has not been loaded yet for context:
猜你喜欢
  • 2012-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多