假设我配置了这两个脚本包:
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 one需要jQuery才能工作。
另一方面,~/Scripts/jQuery
只由jQuery文件组成。
我希望有两个捆绑包,以防视图只需要jQuery而不需要Bootstrap。
但是,我在这里复制代码,我定义了jQuery JavaScript文件路径两次。
有没有办法告诉~/Scripts/Boostrap
包使用或“注入”另一个包?
如下所示:
bundles.Add(new ScriptBundle("~/Scripts/Bootstrap").UseBundle("~/Scripts/jQuery").Include(
"~/Content/Scripts/Bootstrap/bootstrap.js"));
发布于 2014-12-19 06:32:39
您还可以考虑创建一个允许您使用.UseBundle(someBundle)
语法组合包的ComposableBundle
包装器类。
例如,下面的类和扩展方法:
public class ComposableBundle<T> where T : Bundle
{
private T _bundle;
private List<string> _virtualPaths = new List<string>();
public ComposableBundle(T bundle)
{
_bundle = bundle;
}
public string[] VirtualPaths
{
get { return _virtualPaths.ToArray(); }
}
public T Bundle
{
get { return _bundle; }
}
public ComposableBundle<T> Include(params string[] virtualPaths)
{
_virtualPaths.AddRange(virtualPaths);
_bundle.Include(virtualPaths);
return this;
}
public ComposableBundle<T> UseBundle(ComposableBundle<T> bundle)
{
_bundle.Include(bundle.VirtualPaths.ToArray());
return this;
}
}
public static class BundleExtensions
{
public static ComposableBundle<T> AsComposable<T>(this T bundle) where T : Bundle
{
return new ComposableBundle<T>(bundle);
}
public static ComposableBundle<T> Add<T>(this BundleCollection bundles, ComposableBundle<T> bundle) where T: Bundle
{
bundles.Add(bundle.Bundle);
return bundle;
}
}
将允许您这样配置您的包:
var jQueryBundle = bundles.Add(new ScriptBundle("~/bundles/jquery").AsComposable()
.Include("~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryui").AsComposable()
.UseBundle(jQueryBundle)
.Include("~/Scripts/jquery-ui-{version}.js"));
https://stackoverflow.com/questions/27553164
复制相似问题