假设我配置了这两个脚本包:
bundles.Add(new ScriptBundle("~/Scripts/Bootstrap").Include(
"~/Content/Scripts/jQuery/jquery-2.1.1.js",
"~/Content/Scripts/Bootstrap/bootstrap.js"));
bundles.Add(new ScriptBundle("~/Scripts/jQuery").Include(
"~/Content/Scripts/jQuery/jquery-2.1.1.js"));
如您所见,~/Scripts/Boostrap
使用一个 jQuery JavaScript 文件和一个 Bootstrap 文件。这是因为 Bootstrap 需要 jQuery 才能工作。
另一方面,~/Scripts/jQuery
仅由 jQuery 文件组成。
我想要两个包,以防 View 只需要 jQuery 而不需要 Bootstrap。
但是,我在这里复制代码,我定义了 jQuery JavaScript 文件路径两次。
有没有办法告诉 ~/Scripts/Boostrap
包使用或“注入(inject)”另一个包?
像这样:
bundles.Add(new ScriptBundle("~/Scripts/Bootstrap").UseBundle("~/Scripts/jQuery").Include(
"~/Content/Scripts/Bootstrap/bootstrap.js"));
最佳答案
Make a script bundle include another script bundle
不直接使用 Bundling 类。
假设在您的场景中,企业决定为每个请求只向客户端发送一个包。您已决定捆绑每个 Controller (在这个神奇的世界中)所需的所有脚本。你可能会从这样的事情开始:
bundles.Add(new ScriptBundle("~/Scripts/Home")
.Include("~/Content/Scripts/jQuery/jquery-2.1.1.js",
"~/Content/Scripts/Bootstrap/bootstrap.js"
"~/Content/Scripts/Home.js"));
bundles.Add(new ScriptBundle("~/Scripts/Account")
.Include("~/Content/Scripts/jQuery/jquery-2.1.1.js",
"~/Content/Scripts/Bootstrap/bootstrap.js"
"~/Content/Scripts/Account.js"));
然后意识到 .Include(string[])简单地接受一个字符串数组,你可以 DRY你的代码变成这样的:
var commonScripts = new List<string>()
{
"~/Content/Scripts/jQuery/jquery-2.1.1.js",
"~/Content/Scripts/Bootstrap/bootstrap.js"
};
var homeScripts = new List<string>()
{
"~/Content/Scripts/Home.js"
};
bundles.Add(new ScriptBundle("~/bundles/home/")
.Include(commonScripts.Concat(homeScripts).ToArray()));
var accountScripts = new List<string>()
{
"~/Content/Scripts/Account.js"
};
bundles.Add(new ScriptBundle("~/bundles/account/")
.Include(commonScripts.Concat(accountScripts).ToArray()));
我不推荐此解决方案背后的商业原因,但我认为解决它的逻辑可以类似地用于解决您的问题。
如果您认为您可能会有重复项,您还可以:
.Include(commonScripts.Concat(accountScripts)
.Distinct()
.ToArray()));
就我个人而言,我不会将 jQuery 或 BootStrap 包含在 bundle 中,因为它们可以从许多 CDN 在线免费获得; A 表示我使用的带宽较少,B 客户端可能已经下载了我需要的脚本(无论如何 CDN 存在用于常见脚本/样式的原因)。
关于c# - 使脚本包包含另一个脚本包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27553164/