代码之家  ›  专栏  ›  技术社区  ›  David Tuite

有条件地需要commonJS AMD模块中的代码

  •  0
  • David Tuite  · 技术社区  · 14 年前

    我正在尝试为Firefox和Chrome编写一个跨浏览器的扩展。Firefox使用commonJS规范,而Chrome只是像网页一样将所有内容打包到全局命名空间中。

    为了能够编写可重用的代码,我尝试使用requireJS在Chrome扩展中编写代码,这样我就可以编写通用的JS模块,并使它们在这两种环境中都能工作。

    当我需要有条件地要求模块时,我遇到了一个问题。例如,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扩展时,我会收到以下错误:

    Chrome error

    有没有更好的方法来要求具有回退的模块?

    1 回复  |  直到 14 年前
        1
  •  0
  •   Marcelo De Zen    14 年前

    这里有两个注意事项:

    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);
    }