ASP.NET捆绑包如何禁用缩小
我的web.config中都有ASP.NET捆绑包如何禁用缩小,asp.net,asp.net-mvc,asp.net-mvc-4,bundle,asp.net-optimization,Asp.net,Asp.net Mvc,Asp.net Mvc 4,Bundle,Asp.net Optimization,我的web.config中都有debug=“true”,我只是不希望我的包缩小,但我所做的任何事情似乎都不会禁用它。我尝试了启用优化=false,以下是我的代码: //Javascript bundles.Add(new ScriptBundle("~/bundles/MainJS") .Include("~/Scripts/regular/lib/mvc/jquery.validate.unobtrusive.js*") .Include("~/
debug=“true”
,我只是不希望我的包缩小,但我所做的任何事情似乎都不会禁用它。我尝试了启用优化=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))
条件编译指令是您的朋友:
#if DEBUG
var jsBundle = new Bundle("~/Scripts/js");
#else
var jsBundle = new ScriptBundle("~/Scripts/js");
#endif
如果您在web.config中有debug=“true”
,并且正在使用脚本/样式.Render
引用页面中的捆绑包,则应同时关闭捆绑和缩小BundleTable.EnableOptimizations=false
将始终同时关闭绑定和缩小功能(与调试真/假标志无关)
您可能没有使用
脚本/样式.Render
帮助程序吗?如果您通过BundleTable.Bundles.ResolveBundleUrl()
直接呈现对捆绑包的引用,您将始终获得缩小/捆绑的内容。要禁用捆绑和缩小,只需将此文件放在.aspx文件中即可
(这将禁用优化,即使web.config中的debug=true
)
vb.net:
System.Web.Optimization.BundleTable.EnableOptimizations = false
c#net
如果在web.config中放置
EnableOptimizations=true
,即使debug=true
,也会捆绑和缩小,还有一些简单的方法可以手动控制缩小(和其他功能)。它是新的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相同)。只需清除转换,即可关闭捆绑包中的缩小功能
var scriptBundle = new ScriptBundle("~/bundles/scriptBundle");
...
scriptBundle.Transforms.Clear();
我个人发现,当我想将所有脚本捆绑到一个文件中时,这很有用,但在调试阶段需要可读性。结合几个答案,这在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
如果您正在使用LESS/SASS CSS转换,则有一个选项
useNativeMinification
,可以将其设置为false以禁用缩小(在web.config中)。出于我的目的,我只是在需要时在这里对其进行更改,但您可以使用web.config转换在发布版本中始终启用它,或者找到在代码中修改它的方法
<less useNativeMinification="false" ieCompat="true" strictMath="false"
strictUnits="false" dumpLineNumbers="None">
我尝试了很多这样的建议,但似乎都不管用。我浪费了好几个小时才发现这是我的错误:
@Scripts.Render("/bundles/foundation")
无论我尝试了什么,它总是让我缩小并绑定javascript。相反,我应该用这个:
@Scripts.Render("~/bundles/foundation")
额外的“~”成功了。我甚至只在一个实例中再次删除了它,以查看是否真的是这样。那是。。。希望我能为至少一个人省下我在这上面浪费的时间。只是为了补充已经给出的答案,如果您还希望不缩小/混淆/连接某些文件,同时仍允许对其他文件进行完全捆绑和缩小最好的选择是使用自定义呈现器,该呈现器将读取特定捆绑包的内容并在页面中呈现文件,而不是呈现捆绑包的虚拟路径。我个人要求这样做是因为当我的CSS文件被捆绑时,IE 9正在床上$*%@ 非常感谢,这为我创建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);
}
}
}
代替标准:
@Styles.Render("~/Content/css")
我确信为javascript文件创建一个可选的渲染器也不需要更新到这个助手。我结合了其他人在这个问题上给出的一些答案,提出了另一个替代解决方案 目标:始终捆绑文件,在发生
事件时禁用JS和CSS缩小,并始终对CSS捆绑应用自定义转换
我的解决方案:
1) 在web.config中:
2) 在Global.asax应用程序\u 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()));
...
}
如果将以下属性设置为false,则它将禁用绑定和缩小 在Global.asax.cs文件中,添加下面提到的行
protected void Application_Start()
{
System.Web.Optimization.BundleTable.EnableOptimizations = false;
}
当通过VS进行设置时,新框架将获得默认的
web.config
、web.Debug.config
和web.Release.config
,这可能会对将来的用户有用。在web.release.config
中,您可以找到以下行:
<compilation xdt:Transform="RemoveAttributes(debug)" />
这似乎覆盖了我所做的任何内联更改。我把这行注释掉了,我们很高兴(在“发布”版本中看到未缩小的代码)以下是如何在每个包的基础上禁用缩小:
bundles.Add(new StyleBundleRaw("~/Content/foobarcss").Include("/some/path/foobar.css"));
bundles.Add(new ScriptBundleRaw("~/Bundles/foobarjs").Include("/some/path/foobar.js"));
旁注:用于捆绑包的路径不得与发布版本中的任何实际路径一致,否则将无法工作。另外,请确保避免在捆绑包名称中的任何位置使用.js、.css和/或“.”和“u”。保持名称尽可能简单明了,如上面的示例所示
助手类如下所示。请注意,为了使这些类能够经得起未来的考验,我们通过外科手术删除了js/css缩小实例,而不是使用.clear(),并且我们还插入了mime类型设置器转换,如果没有该转换,生产构建必然会遇到麻烦,尤其是在正确移交css包时(firefox和chrome拒绝mime类型设置为默认值“text/html”的css包):
要使整个过程正常运行,您需要安装(通过nuget):
网络润滑脂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>
[...]
protected void Application_Start()
{
System.Web.Optimization.BundleTable.EnableOptimizations = false;
}
<compilation xdt:Transform="RemoveAttributes(debug)" />
bundles.Add(new StyleBundleRaw("~/Content/foobarcss").Include("/some/path/foobar.css"));
bundles.Add(new ScriptBundleRaw("~/Bundles/foobarjs").Include("/some/path/foobar.js"));
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;
}
}
<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>
BundleTable.EnableOptimizations = true;