经过学习LessCSS,咱们知道,Less是须要经过编译才能生成 .css 文件,主要使用三种方式进行编译:css
1)使用第三方编译工具,在项目发布前编译好放在项目中。html
2)在浏览器端解析执行,须要引用 less.js 。git
3)使用第三方程序集在后台动态解析,例如:在.net平台下的dotless。github
这篇随笔记录了如何在.net MVC项目中使用dotless动态解析less。web
在 Content 文件夹中添加 lesses 文件夹,并在该文件夹下添加本身的 .less 文件。(建议使用VS2013及以上版本进行LESS开发,由于vs2013支持LESS、SASS和CoffeeScript模板。)浏览器
1)使用NuGet控制台安装,输入命令以下:mvc
Install-Package dotless
2)使用NuGet管理界面安装app
使用上述方法安装以后,项目会自动引用 dotless.Core 程序集,并会在项目中添加 web.config.install.xdt 文件,该文件中包含了须要添加到 Web.config 配置文件中相关节点。(备注:我参考的资料上都说会自动修改配置文件,可是我测试时并无自动修改配置文件,因此我手动修改的配置文件。)asp.net
1)在 configSections 节点中添加如下节点:less
<section name="dotless" type="dotless.Core.configuration.DotlessConfigurationSectionHandler, dotless.Core" />
2)在 system.web 节点中添加如下节点:
<httpHandlers> <add path="*.less" verb="GET" type="dotless.Core.LessCssHttpHandler, dotless.Core" /> </httpHandlers>
3)在 system.webServer 的 handlers 节点中添加如下节点:
<add name="dotless" path="*.less" verb="GET" type="dotless.Core.LessCssHttpHandler,dotless.Core" resourceType="File" preCondition="" />
4)在 configuration 节点中添加如下节点:
<dotless minifyCss="false" cache="true" web="false" strictMath="false" />
using System.Web.Optimization; namespace LessCssDemo { public class LessTransform : IBundleTransform { public void Process(BundleContext context, BundleResponse response) { response.Content = dotless.Core.Less.Parse(response.Content); response.ContentType = "text/css"; } } }
在 RegisterBundles 方法中添加如下代码:
var lessBundle = new Bundle("~/Content/less").IncludeDirectory("~/Content/lesses", "*.less"); lessBundle.Transforms.Add(new LessTransform()); lessBundle.Transforms.Add(new CssMinify()); bundles.Add(lessBundle);
注意:绑定的名称和路径名称不能相同。若是相同,则在启用样式压缩的状况下对less样式的请求会报403错误。既代码:new Bundle("~/Content/less").IncludeDirectory("~/Content/lesses", "*.less")中标记为红色的代码不能相同。
代码以下:
@Styles.Render("~/Content/less")
以上,就是全部的实现步骤,在此,能够经过修改 <compilation debug="true" targetFramework="4.5" /> 的 debug 属性值为 fales 来测试输出的样式是否压缩。
如下提供使用vs2012建立的源码:LESSCSSDemo.zip
利用CSS预处理技术实现项目换肤功能(less css + asp.net mvc4.0 bundle)