asp.net mvc bundle failed

  • 250
  • 0

 在 RegisterBundles打包 css,最後拿到的結果是原始檔(沒有 minify),只在開頭多了幾行:

/* Minification failed. Returning unminified contents.
(68,60): run-time error CSS1036: Expected expression, found '#'
 */

 

嗯…很明顯的,css寫錯了。
(68,60) 68指的就是發生錯誤的行數,不過要加上開頭錯誤訊息的行數(不在原始檔咩),也就是說,在這個例子裡 (4, xx)才是 css檔的第一行;
然後如果有多個檔案的話,會合併成一個檔案再做 minify,錯誤行數就要自己找在哪個檔案囉。

可以忽略語法檢查,請參考:http://stackoverflow.com/a/25409651/4963421

public class LicensedStyleBundle : Bundle
{
    public LicensedStyleBundle(string virtualPath)
        : base(virtualPath)
    {
        this.Builder = new LicencedStyleBuilder();
    }

    public LicensedStyleBundle(string virtualPath, string cdnPath)
        : base(virtualPath, cdnPath)
    {
        this.Builder = new LicencedStyleBuilder();
    }
}

public class LicencedStyleBuilder : IBundleBuilder
{
    public virtual string BuildBundleContent(Bundle bundle, BundleContext context, IEnumerable<BundleFile> files)
    {
        var content = new StringBuilder();
        foreach (var file in files)
        {
            FileInfo f = new FileInfo(HttpContext.Current.Server.MapPath(file.VirtualFile.VirtualPath));
            CssSettings settings = new CssSettings();
            settings.IgnoreAllErrors = true; //this is what you want
            settings.CommentMode = Microsoft.Ajax.Utilities.CssComment.Important;
            var minifier = new Microsoft.Ajax.Utilities.Minifier();
            string readFile = Read(f);
            string res = minifier.MinifyStyleSheet(readFile, settings);
            content.Append(res);
        }

        return content.ToString();
    }

    public static string Read(FileInfo file)
    {
        using (var r = file.OpenText())
        {
            return r.ReadToEnd();
        }
    }
}

// 用法:
// bundles.Add(new LicensedStyleBundle("~/Content/css").Include("~/Content/site.css"));