ASP.NET Bundles如何禁用缩小

Bac*_*tnz 180 asp.net asp.net-mvc bundle asp.net-mvc-4 asp.net-optimization

我有debug="true"我的web.config(s),我只是不希望我的捆绑缩小,但我做的任何事情似乎都禁用它.我试过了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))
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 152

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

#if DEBUG
            var jsBundle = new Bundle("~/Scripts/js");
#else
            var jsBundle = new ScriptBundle("~/Scripts/js");
#endif
Run Code Online (Sandbox Code Playgroud)

  • 实际上我觉得他已经钉了 - 为了关闭缩小,按照昊使用Bundle,否则使用捆绑和缩小的ScriptBundle,不是吗? (16认同)
  • @ RickAnd-MSFT我认为你误解了这段代码的目的,它允许在调试模式下捆绑+不缩小,在发布模式下捆绑+缩小.使用web.config debug = true/false或EnableOptimizations仅关闭或关闭两者.我读了你的评论并驳回了这个Martin的解决方案,但却发现它实际上是一种非常好的捆绑方式而不会缩小 (6认同)
  • 我已经测试过了,至少在 Firefox 中,mime 类型是正确的 - 即使使用仅捆绑选项 (2认同)

Hao*_*ung 137

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

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

  • 要做到这一点,最简单的方法是将Script/StyleBundles更改为默认情况下没有设置Transform的普通Bundles,这将关闭缩小但仍然捆绑.请注意,您仍然必须将EnableOptimizations设置为true才能进行捆绑. (32认同)
  • 从这个答案来看,我不确定如何关闭_just_ minification并将捆绑保留到位 - 这可能吗? (12认同)
  • 对我来说....对于文件中的'x.js'文件确保文件夹中没有'x.min.js'文件,否则你已经删除了缩小转换..捆绑将服务于'pre'缩小文件,例如,如果你有'angular.js',那么删除'angular.min.js';-) (2认同)
  • `EnableOptimizations = false` - 这段代码属于哪里? (2认同)

man*_*el 84

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

vb.net:

System.Web.Optimization.BundleTable.EnableOptimizations = false
Run Code Online (Sandbox Code Playgroud)

C#.NET

System.Web.Optimization.BundleTable.EnableOptimizations = false;
Run Code Online (Sandbox Code Playgroud)

如果你把EnableOptimizations = true它捆绑并缩小即使debug=trueweb.config中也是如此

  • 这是解决这个问题的唯一方法.我有`debug ="true"`和正确的`Script.Render`但它仍然没有工作.另请注意,这不会为任何.min.js文件提供服务,因此请确保包含依赖代码的未经授权的副本. (2认同)
  • @TCC:我认为vb.net语法应该有一个大写字母'False'我错了吗? (2认同)
  • vb.Net不关心case,False = false,比如.tostring()=.toString() (2认同)

mug*_*lio 66

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

var scriptBundle = new ScriptBundle("~/bundles/scriptBundle");
...
scriptBundle.Transforms.Clear();
Run Code Online (Sandbox Code Playgroud)

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


小智 25

我尝试了很多这些建议,但注意到似乎有效.我浪费了几个小时才发现这是我的错误:

@Scripts.Render("/bundles/foundation")
Run Code Online (Sandbox Code Playgroud)

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

@Scripts.Render("~/bundles/foundation")
Run Code Online (Sandbox Code Playgroud)

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


Jef*_*ian 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
Run Code Online (Sandbox Code Playgroud)


Aga*_*gat 21

还有一些简单的方法可以手动控制缩小(和其他功能).这是新的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();
Run Code Online (Sandbox Code Playgroud)

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


Vin*_*rst 12

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

目标:始终捆绑文件,在事件中禁用JS和CSS缩小<compilation debug="true" ... />并始终将自定义转换应用于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()));
     ...
}
Run Code Online (Sandbox Code Playgroud)


mar*_*ker 6

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

在Global.asax.cs中

protected void Application_Start()
{
    System.Web.Optimization.BundleTable.EnableOptimizations = false;
}
Run Code Online (Sandbox Code Playgroud)


XDS*_*XDS 6

以下是在每个包的基础上禁用缩小的方法:

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

旁注:用于捆绑包的路径不得与已发布版本中的任何实际路径重合,否则将无效。还要确保避免使用 .js、.css 和/或 '.' 和捆绑包名称中的任何位置的“_”。保持名称尽可能简单明了,就像上面的例子一样。

辅助类如下所示。请注意,为了使这些类面向未来,我们手术删除了 js/css 缩小实例而不是使用 .clear() 并且我们还插入了一个 mime-type-setter 转换,否则生产构建必然会遇到麻烦,尤其是当它涉及正确移交 css 包(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;
        }
}
Run Code Online (Sandbox Code Playgroud)

要使这一切正常工作,您需要安装(通过 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  /sf/answers/951798991/  -->
      <modules runAllManagedModulesForAllRequests="true">
         <remove name="BundleModule" />
         <add name="BundleModule" type="System.Web.Optimization.BundleModule" />
      </modules>
      [...]
</system.webServer>
Run Code Online (Sandbox Code Playgroud)

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


BJ *_*tel 5

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

所以如果你发现

BundleTable.EnableOptimizations = true;
Run Code Online (Sandbox Code Playgroud)

转动它false

这确实禁用了缩小,并且还完全禁用了捆绑

  • 这确实禁用了缩小,但它也完全禁用了捆绑,我认为至少应该注意这一点。 (2认同)