在 RequireJS 示例中,它表明您可以从脚本标记引用 app.js(或任何您想要调用的起始文件),如下所示:
<script data-main="js/app.js" src="js/require.js"></script>
由于我无法控制的原因,我无法这样做。模板层中生成了几个需要保留的动态变量。因此,我创建了一个其他模块可以读取的内联“配置”模块。
<script type="text/javascript">
define('config', function() {
return {
markup_id: {
"content": "search",
"page": "index",
"media": "mobile"
},
page_context: {
"siteconfig": {
"mobile_video_player_id": /* */,
"mobile_video_player_key": /* */,
"mobile_ad_site": /* */,
"omniture_mobile_env": /* */,
"searchserver": /* */,
},
"omniture": {
"gn": /* */,
}
}
}
});
</script>
我所做的是为每个模板放置一个内联 require.config。举例(具体路径信息已删除):
<script type="text/javascript">
/* This code is on a template page inside a script tag. */
require.config({
baseUrl: /* */,
paths: {
'jquery': /* */,
'jquery-mobilead': /* */,
'jquery-photogalleryswipe': /* */
},
/* Enforce ordering of jQuery plugins - which require jquery */
shim: {
'jquery-mobilead': {
deps: ['jquery'],
exports: 'jQuery.fn.mobileAd'
},
'jquery-photogalleryswipe': {
deps: ['jquery'],
exports: 'jQuery.fn.photoGallerySwipe'
},
'gallery': {
deps: ['jquery-photogalleryswipe', 'jquery-mobilead']
}
},
urlArgs: 'buildlife=@buildlife@'
});
require( ['jquery', 'site', 'gallery', 'jquery-photogalleryswipe', 'jquery-mobilead'], function($, site, gallery) {
//This function will be called when all the dependencies
//listed above are loaded. Note that this function could
//be called before the page is loaded.
//This callback is optional.
/* Initialize code */
$(document).ready(function() {
/* sitewide code - call the constructor to initialize */
site.init();
/* homepage contains a reference to a function - execute the function */
gallery.initGallery();
});
}
);
</script>
我认为优化器无法优化模板内的代码。
但是根据 RequireJS API 文档,我确实有模块 JS 文件。
/modules/gallery.js
/modules/channel.js
/模块/site.js
/* 等等 */
这些模块确实依赖于其他模块,但这些模块依赖于“config”模块,该模块是与模板内联定义的。如果我针对这些文件运行优化器,优化器是否可以正常工作,因为模板中的模块之一 config 是?
最佳答案
我认为我通过阅读解决了自己的问题 How to load bootstrapped models in Backbone.js while using AMD (require.js)
我已将模板变量重组为 require 全局对象,并在 require.js 之前声明它。现在,模板仍然可以生成这些值,但由于 require.config 和 require 代码可以放入外部 JS 文件中,优化器现在应该能够看到这些文件。我还没有尝试运行优化器。
<script>
/* This script block is in the template */
var require = {
config: {
markup_id: {
"content": "search",
"page": "index",
"media": "mobile"
},
page_context: {
"siteconfig": {
"mobile_video_player_id": /* */,
"mobile_video_player_key": /* */,
"mobile_ad_site": /* */,
"omniture_mobile_env": /* */,
"searchserver": /* */,
},
"omniture": {
"gn": /* */,
}
}
};
</script>
<script data-main="/m/j/main-search" src="/m/j/require.js"></script>
关于javascript - RequireJS 优化器是否可以在没有 "app.js"的情况下以及依赖于内联模块的模块上工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14692876/