ASP.NET Bundles如何禁用缩小

问题描述 投票:176回答:14

我的web.config(s)中都有debug="true",我只是不希望我的捆绑缩小,但我没做什么似乎禁用它。我试过enableoptimisations=false,这是我的代码:

//Javascript
bundles.Add(new ScriptBundle("~/bundles/MainJS")
            .Include("~/Scripts/regular/lib/mvc/jquery.validate.unobtrusive.js*")
            .Include("~/Scripts/regular/lib/mvc/jquery.validate*")
            .Include("~/Scripts/regular/lib/bootstrap.js")
            .IncludeDirectory("~/Scripts/regular/modules", "*.js", true)
            .IncludeDirectory("~/Scripts/regular/pages", "*.js", true)
            .IncludeDirectory("~/Scripts/regular/misc", "*.js", true));

//CSS
bundles.Add(new StyleBundle("~/bundles/MainCSS")
            .Include("~/Content/css/regular/lib/bootstrap.css*")
            .IncludeDirectory("~/Content/css/regular/modules", "*.css", true)
            .IncludeDirectory("~/Content/css/regular/pages", "*.css", true))
asp.net asp.net-mvc asp.net-mvc-4 bundle asp.net-optimization
14个回答
135
投票

如果你在web.config中有debug="true"并且正在使用Scripts/Styles.Render来引用页面中的包,那么应该关闭捆绑和缩小。 BundleTable.EnableOptimizations = false也将始终关闭捆绑和缩小(无论调试真/假标志)。

你可能没有使用Scripts/Styles.Render助手吗?如果您通过BundleTable.Bundles.ResolveBundleUrl()直接渲染对包的引用,您将始终获得缩小/捆绑的内容。


4
投票

只是为了补充已经给出的答案,如果您还希望不缩小/混淆/连接SOME文件,同时仍然允许完全捆绑和缩小其他文件,最好的选择是使用自定义渲染器来读取特定束的内容(s)并在页面中呈现文件而不是呈现包的虚拟路径。我个人要求这个,因为当我的CSS文件被捆绑时,即使关闭缩小功能,IE 9的价格也只是* *%。

非常感谢this article,它给了我代码的起点,我用它来创建一个CSS渲染器,它将渲染CSS的文件,但仍然允许系统渲染我的javascript文件捆绑/缩小/混淆。

创建了静态助手类:

using System;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;

namespace Helpers
{
  public static class OptionalCssBundler
  {
    const string CssTemplate = "<link href=\"{0}\" rel=\"stylesheet\" type=\"text/css\" />";

    public static MvcHtmlString ResolveBundleUrl(string bundleUrl, bool bundle)
    {
      return bundle ? BundledFiles(BundleTable.Bundles.ResolveBundleUrl(bundleUrl)) : UnbundledFiles(bundleUrl);
    }

    private static MvcHtmlString BundledFiles(string bundleVirtualPath)
    {
      return new MvcHtmlString(string.Format(CssTemplate, bundleVirtualPath));
    }

    private static MvcHtmlString UnbundledFiles(string bundleUrl)
    {
      var bundle = BundleTable.Bundles.GetBundleFor(bundleUrl);

      StringBuilder sb = new StringBuilder();
      var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);

      foreach (BundleFile file in bundle.EnumerateFiles(new BundleContext(new HttpContextWrapper(HttpContext.Current), BundleTable.Bundles, bundleUrl)))
      {
        sb.AppendFormat(CssTemplate + Environment.NewLine, urlHelper.Content(file.VirtualFile.VirtualPath));
      }

      return new MvcHtmlString(sb.ToString());
    }

    public static MvcHtmlString Render(string bundleUrl, bool bundle)
    {
      return ResolveBundleUrl(bundleUrl, bundle);
    }
  }

}

然后在剃刀布局文件中:

@OptionalCssBundler.Render("~/Content/css", false)

而不是标准:

@Styles.Render("~/Content/css")

我确信为javascript文件创建一个可选的渲染器也几乎不需要更新到这个帮助器。


4
投票

以下是如何在每个捆绑的基础上禁用缩小:

bundles.Add(new StyleBundleRaw("~/Content/foobarcss").Include("/some/path/foobar.css"));
bundles.Add(new ScriptBundleRaw("~/Bundles/foobarjs").Include("/some/path/foobar.js"));

旁注:用于捆绑包的路径不得与已发布版本中的任何实际路径重合,否则无效。还要确保避免使用.js,.css和/或'。'和'_'在捆绑名称的任何地方。保持名称尽可能简单明了,如上例所示。

帮助程序类如下所示。请注意,为了使这些类能够面向未来,我们通过外科手术删除了js / css缩小实例,而不是使用.clear(),我们还插入了一个mime-type-setter转换,没有生成版本,生成版本就会遇到麻烦,尤其是它适当地移交了css-bundles(firefox和chrome拒绝css包,mime-type设置为“text / html”,这是默认值):

internal sealed class StyleBundleRaw : StyleBundle
{
        private static readonly BundleMimeType CssContentMimeType = new BundleMimeType("text/css");

        public StyleBundleRaw(string virtualPath) : this(virtualPath, cdnPath: null)
        {
        }

        public StyleBundleRaw(string virtualPath, string cdnPath) : base(virtualPath, cdnPath)
        {
                 Transforms.Add(CssContentMimeType); //0 vital
                 Transforms.Remove(Transforms.FirstOrDefault(x => x is CssMinify)); //0
        }
        //0 the guys at redmond in their infinite wisdom plugged the mimetype "text/css" right into cssminify    upon unwiring the minifier we
        //  need to somehow reenable the cssbundle to specify its mimetype otherwise it will advertise itself as html and wont load
}

internal sealed class ScriptBundleRaw : ScriptBundle
{
        private static readonly BundleMimeType JsContentMimeType = new BundleMimeType("text/javascript");

        public ScriptBundleRaw(string virtualPath) : this(virtualPath, cdnPath: null)
        {
        }

        public ScriptBundleRaw(string virtualPath, string cdnPath) : base(virtualPath, cdnPath)
        {
                 Transforms.Add(JsContentMimeType); //0 vital
                 Transforms.Remove(Transforms.FirstOrDefault(x => x is JsMinify)); //0
        }
        //0 the guys at redmond in their infinite wisdom plugged the mimetype "text/javascript" right into jsminify   upon unwiring the minifier we need
        //  to somehow reenable the jsbundle to specify its mimetype otherwise it will advertise itself as html causing it to be become unloadable by the browsers in published production builds
}

internal sealed class BundleMimeType : IBundleTransform
{
        private readonly string _mimeType;

        public BundleMimeType(string mimeType) { _mimeType = mimeType; }

        public void Process(BundleContext context, BundleResponse response)
        {
                 if (context == null)
                          throw new ArgumentNullException(nameof(context));
                 if (response == null)
                          throw new ArgumentNullException(nameof(response));

         response.ContentType = _mimeType;
        }
}

为了使这整件工作你需要安装(通过nuget):

WebGrease 1.6.0+ Microsoft.AspNet.Web.Optimization 1.1.3+

你的web.config应该像这样丰富:

<runtime>
       [...]
       <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-x.y.z.t" newVersion="x.y.z.t" />
       </dependentAssembly>
       <dependentAssembly>
              <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-x.y.z.t" newVersion="x.y.z.t" />
       </dependentAssembly>
        [...]
</runtime>

<!-- setting mimetypes like we do right below is absolutely vital for published builds because for some reason the -->
<!-- iis servers in production environments somehow dont know how to handle otf eot and other font related files   -->
</system.webServer>
        [...]
        <staticContent>
      <!-- in case iis already has these mime types -->
      <remove fileExtension=".otf" />
      <remove fileExtension=".eot" />
      <remove fileExtension=".ttf" />
      <remove fileExtension=".woff" />
      <remove fileExtension=".woff2" />

      <mimeMap fileExtension=".otf" mimeType="font/otf" />
      <mimeMap fileExtension=".eot" mimeType="application/vnd.ms-fontobject" />
      <mimeMap fileExtension=".ttf" mimeType="application/octet-stream" />
      <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
      <mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />
      </staticContent>

      <!-- also vital otherwise published builds wont work  https://stackoverflow.com/a/13597128/863651  -->
      <modules runAllManagedModulesForAllRequests="true">
         <remove name="BundleModule" />
         <add name="BundleModule" type="System.Web.Optimization.BundleModule" />
      </modules>
      [...]
</system.webServer>

请注意,您可能需要采取额外的步骤来使您的css-bundles在字体等方面工作。但这是一个不同的故事。


2
投票

在您的项目中搜索EnableOptimizations关键字

所以,如果你找到了

BundleTable.EnableOptimizations = true;

把它变成false


1
投票

如果您正在使用LESS / SASS CSS转换,则可以选择useNativeMinification,可以将其设置为false以禁用缩小(在web.config中)。出于我的目的,我只是在需要时更改它,但您可以使用web.config转换始终在发布版本上启用它,或者可能找到一种在代码中修改它的方法。

<less useNativeMinification="false" ieCompat="true" strictMath="false"
      strictUnits="false" dumpLineNumbers="None">

提示:这一点的重点是查看您的CSS,您可以在浏览器检查工具中或只打开文件。当启用捆绑时,文件名在每次编译时都会更改,因此我将以下内容放在页面顶部,以便每次更改时都可以在新的浏览器窗口中查看我编译的CSS。

@if (Debugger.IsAttached) 
{
    <a href="@Styles.Url(ViewBag.CSS)" target="css">View CSS</a>
}

这将是一个像https://example.com/Content/css/bundlename?v=UGd0FjvFJz3ETxlNN9NVqNOeYMRrOkQAkYtB04KisCQ1这样的动态URL


更新:我在部署/发布版本期间创建了一个web.config转换,将其设置为true

  <bundleTransformer xmlns="http://tempuri.org/BundleTransformer.Configuration.xsd">
    <less xdt:Transform="Replace" useNativeMinification="true" ieCompat="true" strictMath="false" strictUnits="false" dumpLineNumbers="None">
      <jsEngine name="MsieJsEngine" />
    </less>
  </bundleTransformer>

1
投票

这可能会对未来的某些人有用,因为当通过VS设置时,新框架会获得默认的web.configweb.Debug.configweb.Release.config。在web.release.config你会发现这一行:

<compilation xdt:Transform="RemoveAttributes(debug)" />

这似乎超越了我所做的任何内联更改。我评论了这一行,我们很擅长(在“发布”版本中看到非缩小代码)


148
投票

条件编译指令是你的朋友:

#if DEBUG
            var jsBundle = new Bundle("~/Scripts/js");
#else
            var jsBundle = new ScriptBundle("~/Scripts/js");
#endif

83
投票

要禁用捆绑和缩小,只需将此.aspx文件放入(即使在web.config中使用debug=true,也会禁用优化)

VB.net:

System.Web.Optimization.BundleTable.EnableOptimizations = false

C#.NET

System.Web.Optimization.BundleTable.EnableOptimizations = false;

如果你放EnableOptimizations = true这将捆绑和缩小,即使在web.config中的debug=true


63
投票

您只需清除变换即可关闭捆绑包中的缩小功能。

var scriptBundle = new ScriptBundle("~/bundles/scriptBundle");
...
scriptBundle.Transforms.Clear();

我个人觉得这很有用,因为我想将所有脚本捆绑在一个文件中,但在调试阶段需要可读性。


25
投票

我尝试了很多这些建议,但似乎没有任何效果。我浪费了几个小时才发现这是我的错误:

@Scripts.Render("/bundles/foundation")

它总是让我缩小和捆绑javascript,无论我尝试什么。相反,我应该使用这个:

@Scripts.Render("~/bundles/foundation")

额外的'〜'做到了。我甚至只在一个实例中再次删除它,看看是不是真的。这是......希望我浪费了至少一个人的时间。


23
投票

结合几个答案,这适用于ASP.NET MVC 4。

        bundles.Add(new ScriptBundle("~/Scripts/Common/js")
            .Include("~/Scripts/jquery-1.8.3.js")
            .Include("~/Scripts/zizhujy.com.js")
            .Include("~/Scripts/Globalize.js")
            .Include("~/Scripts/common.js")
            .Include("~/Scripts/requireLite/requireLite.js"));

        bundles.Add(new StyleBundle("~/Content/appLayoutStyles")
            .Include("~/Content/AppLayout.css"));

        bundles.Add(new StyleBundle("~/Content/css/App/FunGrapherStyles")
            .Include("~/Content/css/Apps/FunGrapher.css")
            .Include("~/Content/css/tables.css"));

#if DEBUG
        foreach (var bundle in BundleTable.Bundles)
        {
            bundle.Transforms.Clear();
        }
#endif

20
投票

还有一些简单的方法可以手动控制缩小(和其他功能)。这是新的CssMinify()转换器使用,如下所示:

// this is in case when BundleTable.EnableOptimizations = false;
var myBundle = new StyleBundle("~/Content/themes/base/css")
    .Include("~/Content/themes/base/jquery.ui.core.css" /* , ... and so on */);
myBundle.Transforms.Add(new CssMinify());
bundles.Add(myBundle);

// or you can remove that transformer in opposite situation
myBundle.Transforms.Clear();

当你想要一些特殊部分只是为了缩小时,这很方便。比方说,你正在使用一些标准(jQuery)样式,这些样式正在你的脚下(对它们采取大量过多的浏览器请求),但是你想要保持自己的样式表。 (相同 - 使用javascript)。


12
投票

我在这个问题中结合了其他人给出的一些答案,提出了另一种替代解决方案。

目标:始终捆绑文件,在<compilation debug="true" ... />事件中禁用JS和CSS缩小并始终将自定义转换应用于CSS捆绑包。

我的解决方案

1)在web.config中:<compilation debug="true" ... />

2)在Global.asax Application_Start()方法中:

 protected void Application_Start() {
     ...
     BundleTable.EnableOptimizations = true; // Force bundling to occur

     // If the compilation node in web.config indicates debugging mode is enabled
     // then clear all transforms. I.e. disable Js and CSS minification.
     if (HttpContext.Current.IsDebuggingEnabled) {
         BundleTable.Bundles.ToList().ForEach(b => b.Transforms.Clear());
     }

      // Add a custom CSS bundle transformer. In my case the transformer replaces a
      // token in the CSS file with an AppConfig value representing the website URL
      // in the current environment. E.g. www.mydevwebsite in Dev and
      // www.myprodwebsite.com in Production.
      BundleTable.Bundles.ToList()
          .FindAll(x => x.GetType() == typeof(StyleBundle))
          .ForEach(b => b.Transforms.Add(new MyStyleBundleTransformer()));
     ...
}

6
投票

如果将以下属性设置为false,则它将禁用捆绑和缩小。

在Global.asax.cs文件中,添加如下所述的行

protected void Application_Start()
{
    System.Web.Optimization.BundleTable.EnableOptimizations = false;
}
© www.soinside.com 2019 - 2024. All rights reserved.