首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使一个脚本包包含另一个脚本包

使一个脚本包包含另一个脚本包
EN

Stack Overflow用户
提问于 2014-12-19 02:20:30
回答 1查看 9.6K关注 0票数 21

假设我配置了这两个脚本包:

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"));
EN

回答 1

Stack Overflow用户

发布于 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"));
票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27553164

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档