RequireJS使用多个data-main [英] RequireJS using multiple data-main's
问题描述
我正在使用RequireJs 2.0(或尝试使用)。
I'm using RequireJs 2.0 (or attempting to use).
目前,我的资产被分组为常规和自定义部分。所有页面都应该使用常规脚本,而只有一些页面应该使用自定义。
Currently, my assets are grouped into to parts, "General" and "Custom". All pages, should use the General scripts, while only some pages should use the Custom.
从我可以告诉RequireJs,接受一个 data-main
值来保存你的配置,基本上你的模块需要。如果所有页面都使用相同的资源,这是好的,但我如何为自定义页面添加额外的 data-main
脚本?
From what I can tell RequireJs, accepts one data-main
value which holds your config and basically your module require's. This is fine if all pages use the same assets, but how would I add an additional data-main
script for Custom pages?
谢谢!
推荐答案
使用 data-main
用于加载常规脚本的属性。在自定义页面上,无论您何时要执行需要自定义模块的操作,只需将其包装在 require
调用中。您的母版页(或模板或布局或服务器平台上调用的任何内容)将具有以下内容:
Use your data-main
attribute to load your General script. On the custom pages, wherever you're about to do something that requires a Custom module, just wrap it in a require
call. Your master page (or template or layout or whatever it's called on your server platform) would have this:
<html><head>
<script language="javascript" src="require.js" data-main="general" ></script>
</head>
您的自定义页面标记可能如下所示(来自内存的语法;仔细检查!)
Your custom page markup can look like this (syntax from memory; double-check!)
<p class="funny">I'm a funny paragraph</p>
<script language="javascript">
require(['funny-stuff'], function(fs) {
fs.doSomthing();
});
</script>
有趣的东西
模块只会获得由要求它的页面加载。如果您不希望或不能在某些页面上使用单独的标记,则可以通过在<$中包装 require
来动态加载主脚本中的依赖项。 c $ c> if 声明。在 general.js
中:
The funny-stuff
module would only get loaded by pages that ask for it. If you don't want to or can't have separate markup on some pages, you can dynamically load a dependency from your main script by wrapping a require
call inside an if
statement. Within general.js
:
// Determine if we need the custom module
if (isFunnyPage()) {
require(['funny-stuff'], function(fs) {
fs.doSomething();
});
}
运行优化器时必须小心,因为它会找到中引用的依赖项
调用,默认情况下将其与主文件打包在一起。因此,您需要配置优化器以排除自定义模块。
You do have to be careful when you run the optimizer, because it will find the dependency referenced in the require
call, and by default package it with your main file. So you would need to configure the optimizer to exclude the custom modules.
这篇关于RequireJS使用多个data-main的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!