是否有任何功能可以根据当前项目环境(例如开发或生产)加载不同的文件?我的意思是,这有助于我透明地加载缩小或完整的文件.我读到了关于多版本加载的内容,但是多版本化意味着我需要指定文件的版本.
例如,我的模块有module.js文件.在这个文件中我需要加载jQuery:
例如,我的模块有module.js文件.在这个文件中我需要加载jQuery:
require(['jquery]);
但我有jQuery的缩小版和完整版,我想加载不同的文件.我在配置中考虑这样的事情:
require.config({ paths: { 'jquery' : function(){ if( MODE == 'DEV' ){ return 'jquery'; }else{ return 'jquery.min' } } } });
或者,也许,类似的东西.
解决方法
如果您使用
the r.js optimizer,则可以为您处理此过程.在您的脚本文件夹中,为了开发目的,将所有模块,库和其他代码保持未压缩状态.我经常有这样的事情
scripts/ lib/ modules/
准备部署时,创建build.js并配置各种选项.我将举例说明我使用过的类似配置:
({ baseUrl: '../scripts',dir: '../scripts.min',paths: { 'jquery': 'lib/jquery' },removeCombined: true,optimize: 'uglify',preserveLicenseComments: false,uglify: { max_line_length: 3500,no_copyright: true },modules: [ { name: 'module1' },{ name: 'module2',exclude: ['jquery'] } ] })
关于这个选项can be found in this example configuration的更多细节,但我会提请注意dir和removeCombined
dir显然是你的脚本最终会在哪里.我倾向于在我的脚本旁边创建一个带有后缀.min或类似内容的文件夹.然后,当您准备好投入生产时,只需将您的require config baseUrl更改为scripts.min即可
require.config({ baseUrl: '/scripts.min' // Now the site will load scripts from the optimised folder // Other options })
默认情况下,r.js将复制所有脚本,无论它们是否已经合并到另一个js文件中.将removeCombined设置为true将确保您的scripts.min文件夹仅包含生产所需的文件.