51

我正在尝试使用捆绑来组合和缩小一些 CSS 文件。在我的 Global.aspx.csApplication_Start我有以下内容:

    var jsBundle = new Bundle("~/JSBundle", new JsMinify());
    jsBundle.AddDirectory("~/Scripts/", "*.js", false);
    jsBundle.AddFile("~/Scripts/KendoUI/jquery.min.js");
    jsBundle.AddFile("~/Scripts/KendoUI/kendo.web.min.js");
    BundleTable.Bundles.Add(jsBundle);

    var cssBundle = new Bundle("~/CSSBundle", new CssMinify());
    cssBundle.AddDirectory("~/Content/", "*.css", false);
    cssBundle.AddDirectory("~/Content/themes/base/", "*.css", false);
    cssBundle.AddFile("~/Styles/KendoUI/kendo.common.min.css");
    cssBundle.AddFile("~/Styles/KendoUI/kendo.default.min.css");
    BundleTable.Bundles.Add(cssBundle);

在我的 .cshtml 文件中,我有以下内容:

<link href="/CSSBundle" rel="stylesheet" type="text/css" />
<script src="/JSBundle" type="text/javascript"></script>

但是,当我查看我的 bundles CSS 文件的源代码时,它具有以下内容:

/* Minification failed. Returning unminified contents.
(40,1): run-time error CSS1019: Unexpected token, found '@import'
(40,9): run-time error CSS1019: Unexpected token, found '"jquery.ui.base.css"'

.... 更多

关于如何解决这个问题的任何想法?

我确实将其缩小到以下行:

cssBundle.AddDirectory("~/Content/themes/base/", "*.css", false);

如果我只有那行代码,我会得到同样的错误。

4

2 回答 2

48

这里有几个问题:

  1. css 问题是由于包含 jquery.ui.all.css,因为默认的 minifier 不支持以下导入,无论如何这不是您想要做的,因为它会双重包含所有 jquery ui css 文件。所以你想要做的不是使用 *.css,而是明确列出你想要包含的 jquery ui 文件:

     bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
            "~/Content/themes/base/jquery.ui.core.css",
            "~/Content/themes/base/jquery.ui.resizable.css",
            "~/Content/themes/base/jquery.ui.selectable.css",
            "~/Content/themes/base/jquery.ui.accordion.css",
            "~/Content/themes/base/jquery.ui.autocomplete.css",
            "~/Content/themes/base/jquery.ui.button.css",
            "~/Content/themes/base/jquery.ui.dialog.css",
            "~/Content/themes/base/jquery.ui.slider.css",
            "~/Content/themes/base/jquery.ui.tabs.css",
            "~/Content/themes/base/jquery.ui.datepicker.css",
            "~/Content/themes/base/jquery.ui.progressbar.css",
            "~/Content/themes/base/jquery.ui.theme.css"));
    
  2. 其次,您希望使用 Script/Styles.Render 方法,而不是像您正在做的那样显式引用捆绑 url,因为在调试模式下,帮助程序不会自动捆绑/缩小和呈现对每个脚本/样式资产的单独引用,并且还将捆绑内容的指纹附加到 url 中,以便浏览器缓存可以正常工作。

    @Scripts.Render("~/JSBundle") and @Styles.Render("~/CSSBundle")
    
  3. 您还可以使用 StyleBundle/ScriptBundle,它只是语法糖,无需传入新的 Css/JsMinify。

您还可以查看本教程以获取更多信息: 捆绑教程

于 2012-08-28T20:33:35.073 回答
10

或者,如果您当然需要这种灵活性,您可以为 CssMinify 编写自己的 BundleTransform。因此,例如,您在 BundleConfig.cs 中的代码如下所示:

using System;
using System.Web.Optimization;
using StyleBundle = MyNamespace.CustomStyleBundle;

public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new StyleBundle("~/Content/themes/base/css")
            .IncludeDirectory("~/Content/themes/base", "*.css"));
    }
}

那么你需要添加的是:

public class CustomStyleBundle : Bundle
{
    public CustomStyleBundle(string virtualPath, IBundleTransform bundleTransform = null)
        : base(virtualPath, new IBundleTransform[1]
            {
                bundleTransform ?? new CustomCssMinify()
            })
    {
    }

    public CustomStyleBundle(string virtualPath, string cdnPath, IBundleTransform bundleTransform = null)
        : base(virtualPath, cdnPath, new IBundleTransform[1]
            {
                bundleTransform ?? new CustomCssMinify()
            })
    {
    }
}

public class CustomCssMinify : IBundleTransform
{
    private const string CssContentType = "text/css";

    static CustomCssMinify()
    {
    }

    public virtual void Process(BundleContext context, BundleResponse response)
    {
        if (context == null)
            throw new ArgumentNullException("context");
        if (response == null)
            throw new ArgumentNullException("response");
        if (!context.EnableInstrumentation)
        {
            var minifier = new Minifier();
            FixCustomCssErrors(response);
            string str = minifier.MinifyStyleSheet(response.Content, new CssSettings()
            {
                CommentMode = CssComment.None
            });
            if (minifier.ErrorList.Count > 0)
                GenerateErrorResponse(response, minifier.ErrorList);
            else
                response.Content = str;
        }
        response.ContentType = CssContentType;
    }

    /// <summary>
    /// Add some extra fixes here
    /// </summary>
    /// <param name="response">BundleResponse</param>
    private void FixCustomCssErrors(BundleResponse response)
    {
        response.Content = Regex.Replace(response.Content, @"@import[\s]+([^\r\n]*)[\;]", String.Empty, RegexOptions.IgnoreCase | RegexOptions.Multiline);
    }

    private static void GenerateErrorResponse(BundleResponse bundle, IEnumerable<object> errors)
    {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.Append("/* ");
        stringBuilder.Append("CSS Minify Error").Append("\r\n");
        foreach (object obj in errors)
            stringBuilder.Append(obj.ToString()).Append("\r\n");
        stringBuilder.Append(" */\r\n");
        stringBuilder.Append(bundle.Content);
        bundle.Content = stringBuilder.ToString();
    }
}

如果您需要更多修复/错误,您可以在 FixCustomCssErrors 方法中扩展此逻辑。

于 2013-02-25T18:17:20.253 回答