51

I'm trying to use bundling to combine & minify some CSS files. In my Global.aspx.cs Application_Start I have the following:

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

And in my .cshtml file I have the following:

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

However, when I view the source of my bundles CSS file, it has the following:

/* 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"'

.... lots more

Any ideas on how to resolve this?

I did narrow it down to the following line:

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

If I only have that line of code I get the same errors.

Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
Kyle
  • 17,317
  • 32
  • 140
  • 246

2 Answers2

48

There are a few issues here:

  1. The css issue is due to including the jquery.ui.all.css, as the default minifier doesn't support following imports, and this is not what you want to do anyways as it would double include all of the jquery ui css files. So what you want to do instead is not use *.css, and instead explicitly list what jquery ui files you want to include:

     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. Secondly you want to be using the Script/Styles.Render methods rather than explicitly referencing the bundles url as you are doing, as the helpers will automatically not bundle/minify and render individual references to each script/style asset when in debug mode, and also append a fingerprint for the bundle contents into the url so browser caching will work propertly.

    @Scripts.Render("~/JSBundle") and @Styles.Render("~/CSSBundle")
    
  3. You can also use StyleBundle/ScriptBundle which is just syntaxtic sugar for not having to pass in new Css/JsMinify.

You can also check out this tutorial for more info: Bundling Tutorial

Robert Koritnik
  • 103,639
  • 52
  • 277
  • 404
Hao Kung
  • 28,040
  • 6
  • 84
  • 93
  • 2
    You missed "~/Content/themes/base/jquery.ui.menu.css" and "~/Content/themes/base/jquery.ui.spinner.css". – Stef Heyenrath Nov 12 '12 at 09:56
  • 3
    Well, it also fails to bundle when it encounters things like @-webkit-keyframes, so it's not just failing on @import. – Triynko Nov 11 '15 at 18:41
  • i used ScriptBundle for bundling CSS abd got [this](https://groups.google.com/forum/#!topic/glow-users/pDf8CzVa-Jc) error , **Be sure** to use `ScriptBundle` for Scripts and `StyleBundle` for CSS – Shaiju T Feb 24 '16 at 17:18
10

Or what you can do is to write your own BundleTransform for CssMinify if of course you need such a flexibility. So, for example your code in BundleConfig.cs looks like:

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

Then what you need to add is:

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();
    }
}

And if you need some more fixes/errors you can extend this logic in FixCustomCssErrors method.

Hakan Fıstık
  • 16,800
  • 14
  • 110
  • 131
Andrey Borisko
  • 4,511
  • 2
  • 22
  • 31
  • 4
    This solution effectively removes all `@import` from the files, correct? That will probably not make the page render very well. – MEMark Nov 19 '14 at 15:31
  • 1
    It also doesn't address the fact that it not only fails on @import, but also on @-webkit-keyframes, and other perfectly valid CSS that it doesn't recognize. Useless. Meanwhile, Flash solved this a decade ago, delivering a single SWF file, which was even compressed. I tried to create a vertically-wrapped column in HTML (another 'Holy Grail', because it's so difficult to do something so simple), only to learn that although 'column-count' CSS was defined in 2001, it's 2015 and it's still only half-implemented in Chrome. Flexbox sucks too, requiring pre-defined height to work. – Triynko Nov 11 '15 at 18:41
  • which Bundler version do you use? I have VS 2015 with [Microsoft ASP.NET Web Optimization 1.1.3](https://www.nuget.org/packages/Microsoft.AspNet.Web.Optimization/1.1.3). I don't have any errors with `@-webkit-keyframes` and I see it in buundle's output. – Andrey Borisko Nov 11 '15 at 19:33