ASP.NET Bundles cómo desactivar la minificación


Tengo debug="true"en ambos mi web.config (s) , y simplemente no quiero minificar mis paquetes, pero nada de lo que hago parece desactivarlo. He intentado enableoptimisations=false, aquí está mi código:

//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))
Author: Mosh Feu, 2012-08-14

14 answers

Si tienes debug="true"en web.config y están usando Scripts/Styles.Render para hacer referencia a los paquetes en sus páginas, eso debería desactivar tanto la agrupación como la minificación. BundleTable.EnableOptimizations = false siempre desactivará tanto la agrupación como la minificación (independientemente de la bandera de depuración verdadera/falsa).

¿Acaso no estás usando los Scripts/Styles.Render ayudantes? Si está renderizando directamente referencias al paquete a través de BundleTable.Bundles.ResolveBundleUrl(), siempre obtendrá el contenido minificado/incluido.

 127
Author: Hao Kung,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-19 06:01:09

Las directivas de compilación condicional son tu amigo:

#if DEBUG
            var jsBundle = new Bundle("~/Scripts/js");
#else
            var jsBundle = new ScriptBundle("~/Scripts/js");
#endif
 142
Author: Martin Devillers,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-14 16:23:59

Para desactivar la agrupación y la minificación, simplemente pon esto en tu .archivo aspx (esto deshabilitará la optimización incluso si {[2] {} en[6]}web.config )

Vb.net:

System.Web.Optimization.BundleTable.EnableOptimizations = false

C#.net

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

Si pones EnableOptimizations = true se bundle y minify incluso si {[2] {} en[6]}web.config

 82
Author: manuel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-09 05:32:50

Puedes desactivar la minificación en tus paquetes simplemente borrando tus transformaciones.

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

Personalmente encontré esto útil cuando quería agrupar todos mis scripts en un solo archivo, pero necesitaba legibilidad durante las fases de depuración.

 61
Author: muglio,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-16 16:51:18

Probé muchas de estas sugerencias, pero notarlas parecía funcionar. He perdido bastantes horas solo para descubrir que este fue mi error:

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

Siempre me han minificado y empaquetado javascript, no importa lo que probé. En su lugar, debería haber usado esto:

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

El extra '~' lo hizo. Incluso lo he eliminado de nuevo en una sola instancia para ver si eso era realmente. Lo fue... espero poder ahorrarle al menos a una persona las horas que desperdicié en esto.

 24
Author: Nick,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-02 19:42:03

Combinar varias respuestas, esto funciona para mí en 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
 22
Author: Jeff Tian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-18 02:19:49

También hay una forma sencilla de controlar la minificación (y otras características) manualmente. Es nuevo transformador CssMinify () usando, así:

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

Eso es conveniente cuando desea tener algunos paquetes de parte especial solo para ser minificado. Digamos que está utilizando algunos estilos estándar (jQuery), que se están poniendo bajo sus pies (recibiendo muchas solicitudes excesivas del navegador), pero desea mantener sin minificar su propia hoja de estilos. (Lo mismo-con javascript).

 19
Author: Agat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-29 22:29:15

Combiné algunas respuestas dadas por otros en esta pregunta para llegar a otra solución alternativa.

Objetivo: Agrupar siempre los archivos, deshabilitar la minificación JS y CSS en el caso de que <compilation debug="true" ... /> y aplicar siempre una transformación personalizada al paquete CSS.

Mi solución:

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

2) En el Global.asax Application_Start() método:

 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()));
     ...
}
 12
Author: Vince Horst,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-05 23:43:19

Si establece la siguiente propiedad en false, deshabilitará tanto la agrupación como la minificación.

En Global.asax.cs

protected void Application_Start()
{
    System.Web.Optimization.BundleTable.EnableOptimizations = false;
}
 5
Author: marvelTracker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-16 10:38:23

Solo para complementar las respuestas ya dadas, si también desea NO minificar/ofuscar/concatenar ALGUNOS archivos mientras todavía permite la agrupación completa y la minificación para otros archivos la mejor opción es ir con un renderizador personalizado que leerá el contenido de un paquete particular(s) y renderizará los archivos en la página en lugar de renderizar la ruta virtual del paquete. Yo personalmente requirió esto porque IE 9 era IE * % @ing la cama cuando mis archivos CSS estaban siendo liados incluso con minificación desactivada .

Muchas gracias a este artículo, que me dio el punto de partida para el código que utilicé para crear un Renderizador CSS que renderizaría los archivos para el CSS pero aún así permitir que el sistema renderice mis archivos javascript empaquetados/minificados/ofuscados.

Se creó la clase auxiliar estática:

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

}

Luego en el archivo de maquetación de razor:

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

En lugar del estándar:

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

Estoy seguro de crear un renderizador opcional para los archivos javascript también necesitarían poco para actualizarse a este ayudante.

 4
Author: James Eby,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-27 04:56:15

He aquí cómo desactivar la minificación por paquete:

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

Nota lateral: Las rutas utilizadas para tus paquetes no deben coincidir con ninguna ruta real en tus compilaciones publicadas, de lo contrario nada funcionará. También asegúrese de evitar el uso .js, .css y/o '.'y' _ ' en cualquier lugar del nombre del paquete. Mantenga el nombre tan simple y directo como sea posible, como en el ejemplo anterior.

Las clases auxiliares se muestran a continuación. Tenga en cuenta que con el fin de hacer estas clases a prueba de futuro, eliminamos quirúrgicamente las instancias de reducción de js / css en lugar de usarlas .clear () y también insertamos una transformación mime-type-setter sin la cual las compilaciones de producción están destinadas a tener problemas, especialmente cuando se trata de entregar correctamente los paquetes css (firefox y chrome rechazan los paquetes css con el tipo mime establecido en "text/html" que es el predeterminado):

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

Para que todo esto funcione necesitas instalar (vía nuget):

WebGrease 1.6.0+ Microsoft.AspNet.Web.Optimización 1.1.3+

Y su web.config debe enriquecerse así:

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

Tenga en cuenta que es posible que tenga que tomar medidas adicionales para hacer que sus paquetes CSS funcionen en términos de fuentes, etc. Pero esa es otra historia.

 3
Author: xDisruptor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-14 19:02:39

Si está utilizando la transformación CSS LESS/SASS, hay una opción useNativeMinification que se puede establecer en false para deshabilitar la minificación (en web.config). Para mis propósitos, solo lo cambio aquí cuando lo necesito, pero podrías usar web.config transformaciones para siempre habilitarlo en la compilación de la versión o tal vez encontrar una manera de modificarlo en el código.

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

Consejo: El objetivo de esto es ver su CSS, lo que puede hacer en las herramientas de inspección del navegador o simplemente abriendo el archivo. Cuando la agrupación está habilitada ese nombre de archivo cambia en cada compilación, así que puse lo siguiente en la parte superior de mi página para que pueda ver mi CSS compilado eaily en una nueva ventana del navegador cada vez que cambie.

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

Esta será una URL dinámica algo así como https://example.com/Content/css/bundlename?v=UGd0FjvFJz3ETxlNN9NVqNOeYMRrOkQAkYtB04KisCQ1


Actualización: He creado una web.transformación de configuración para establecerla en true para mí durante la compilación de implementación / lanzamiento

  <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
Author: Simon_Weaver,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-22 19:21:01

Esto puede ser útil para alguien en el futuro, ya que el nuevo marco, cuando se configura a través de VS, obtiene un valor predeterminado web.config, web.Debug.config y web.Release.config. En el web.release.config encontrará esta línea:

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

Esto parecía anular cualquier cambio en línea que hiciera. Comenté esta línea y estábamos gravy (en términos de ver código no minificado en una compilación "release")

 1
Author: Mutmatt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-20 23:02:10

Busca la palabra clave EnableOptimizations en tu proyecto

Así que si encuentras

BundleTable.EnableOptimizations = true;

Gíralo false.

 1
Author: BJ Patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-06 06:53:37