【问题标题】:how to optimize project using requireJS if we have defined some maps in config?如果我们在配置中定义了一些地图,如何使用 requireJS 优化项目?
【发布时间】:2012-09-13 11:29:22
【问题描述】:

我的 main 中有一个 require.config,如下所示。

require.config({
baseUrl:'scripts/',

 paths:{  
        jquery:'shell/lib/jquery/jquery-1.7.1'
     // many libraries and modules are aliased here

 },
 map:{
  '*':{
      'underscore':'shell/lib/underscore/underscore'
            // a few other modules are mapped here
  }
 }     

});

我这样做是因为 map 中定义的文件使用相对路径的内部依赖项(在它们各自的文件夹中)。 现在,当我运行优化器时,路径中定义的模块保存为模块 ID,例如保存为 jquery 的 jquery,而映射中的模块正在获取完整路径,例如 'underscore' 为 'shell/lib/underscore/下划线”而不是“下划线”。

这会导致问题,因为我也在其他模块中使用“下划线”,并且优化后的文件有“下划线”而不是“shell/lib/underscore/underscore”。

当我们提供地图配置或我缺少的东西时,是否有一些特定的优化方法?请告诉我如何解决它。

谢谢

【问题讨论】:

  • 不太清楚您为什么要尝试将下划线放入地图中。当您的应用程序中的不同模块依赖于不同版本的 Underscore 时,地图很有用。如果您的所有应用程序都依赖于一个版本的 Underscore,请将其输入路径。请在 cmets 中澄清,我会尽力帮助您。
  • 这个下划线是写在下划线库上的一个包装器 .js 文件,上面写着 require[("./underscore-1.3.3").... 这样做是因为一个团队测试并定义了哪个开源库使用和其他团队使用它们。在编写像 Animation.js 这样的开源库的自定义扩展时,也会使用这种实现。提前致谢。

标签: javascript optimization module requirejs


【解决方案1】:

我不确定是否理解这个问题:

这会导致问题,因为我也在其他模块中使用“下划线”,并且优化后的文件有“下划线”而不是“shell/lib/underscore/underscore”。

这似乎是预期的行为,您将underscore 映射到所有模块的该路径。所以基本上你告诉r.js:每次你找到underscore依赖时,将它重写为shell/lib/underscore/underscore。如果你的模块使用“内部路径”并且你想做相反的事情(让它们引用underscore),你需要做相反的映射:

 'some/path/underscore': 'underscore'

在这种情况下,所有模块都将指向同一个下划线模块。甚至那些使用一些奇怪路径作为下划线的人。

在极端情况下,您需要控制r.js 如何在磁盘上写入模块。您可以使用onBuildWrite 属性(请参阅https://github.com/jrburke/r.js/blob/master/build/example.build.js#L517)。

例如:

onBuildWrite: function ( moduleName, path, contents ) {
    if ( path === './src/somefile.js' ) {
          return contents.replace(/^define\('src\/underscore'/, "define('underscore'");
    } else {
          return contents;
    }
}

这个例子是一个告诉r.js的“hack”:当你处理somefile.js时,用underscore替换src/underscore(这正是你对map所做的......但只是为了向你展示如何你可以使用onBuildWrite 做讨厌的事情)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-07
    • 1970-01-01
    • 1970-01-01
    • 2017-06-13
    • 1970-01-01
    相关资源
    最近更新 更多