bootstrap less sass导入styles.less文件出现问题,请问一下怎么回事啊?

Bootstrap&Less&学习笔记
最近学习 Twitter Bootstrap 的使用, 趁著记忆犹新,把 Less 的重点整理了一下。
简单来说,Less 就是让你在网页设计的时候,可以更方便地写 CSS 的工具。
Less官网的说明:
LESS 将 CSS 赋予了动态语言的特性,如 变量,
继承,运算,函数. LESS
既可以在客户端上运行(支持IE 6+, Webkit,
Firefox),也可以借助Node.js或者Rhino在服务端运行。
也就是说,你可以透过 Less 的语法使用 变量, 继承, 运算 和函数 这些工具,再通过编译之后,less 就可以转成一般的
CSS,于是让设计 CSS 这件事可以更加地有弹性。
「为什么设计 CSS 需要更加有弹性呢?」你问,「CSS 不是一个纯文字档写完就好了吗?有必要搞得还需要编译那么复杂吗?」
是的,没错,CSS 原本就只是一个说明样式的纯文字档,你可能觉得用 textmate 或 dreamwever 或 notepad
写完就好了。但可惜的是,web design 常常不是一个用过一次就丢的东西,你可能三不五时需要去修改它。
此外,就算是在刚开始设计的阶段,Less 可以提供你很多方便的工具,人家写 5 行你只要写 1 行;人家改一个色码要改 9
个地方(搞不好还漏掉了一个),你只要改一个地方,而且全部没有漏,这样一来一回,效率的差别就差很大了 。
less 提供的主要功能
个人觉得,变量是 Less 最重要的功能。举例来说,在设计的时候,我们常常会在很多个地方使用相同的色码
(或是用很相近的颜色)来塑造整体的感觉,例如在 h1, h2, h3, button, link hover color, ….
在以往设计 CSS 的时候,我们可能需要在这些 tag 的样式里面做各自的设定。但现在通过变量 ,我们可以在最上面宣告一个 base
color, 然后在其他地方反覆使用这个 base color。这样网站在做设计上的调整时,就可以省下很多时间。
举例来说,下面是 Less 的写法:
@color: #4D926F;
下面是编译出来的 CSS:
color: #4D926F;
color: #4D926F;
mixins让你可以重覆利用某些样式的宣告,你可以在 A 样式里面包括另一个 B class, 所有被 B class
的样式都会被嵌入进来
A 这个样式设定。
.bordered { border-top:
dotted 1px border-bottom: solid 2px }
那如果我们现在需要在其他class中引入那些通用的属性集,那么我们只需要在任何class中像下面这样调用就可以了:
#menu a { color: #111;
.bordered; }
下面是转出来的 CSS:
color: #111;
border-top: dotted 1px
border-bottom: solid 2px
带参数混合
这个最好用的地方就是在简化一些比较不好写的 css, 例如 CSS3 的圆角设定,目前因为浏览器的语法尚未统一,你需要写:
border-radius: 5
-webkit-border-radius: 5
-moz-border-radius: 5
border-radius: 10
-webkit-border-radius: 10
-moz-border-radius: 10
但通过Less, 你只要写:
.border-radius (@radius) {
border-radius: @
-moz-border-radius: @
-webkit-border-radius: @
.border-radius(4px);
.border-radius(6px);
是的,正如你所看到, mixins 不只可以把某个 class include 进来,甚至可以在 include
的时候指定一个参数!!猜猜看现在如果你又需要一个 10 px 的 border-radius, 你还需要写几行?
@arguments&变量
@arguments包含了所有传递进来的参数。
例如 CSS3 的阴影设定,目前因为浏览器的语法尚未统一,你需要写:
.boxShadow (@x: 0, @y: 0, @blur: 1px, @shadow: #000) {
-webkit-box-shadow: @x @y @blur @
-moz-box-shadow: @x @y @blur @
box-shadow: @x @y @blur @
如果你不想单独处理每一个参数的话就可以像这样写:
.box-shadow (@x: 0, @y: 0, @blur: 1px, @color: #000) {
& box-shadow: @
& -moz-box-shadow: @
& -webkit-box-shadow: @
运用到#nav上:
.box-shadow(2px, 5px);
下面是转出来的 CSS:
& box-shadow: 2px 5px 1px #000;
& -moz-box-shadow: 2px 5px 1px #000;
& -webkit-box-shadow: 2px 5px 1px #000;
3.嵌套规则
CSS selector 里面有一个重要的用法,叫做后代选择器 (Descendant selectors)
也就是说,你可以用下面这段样式去设定你 ID=header 这个 container 中, h1, p, p 下面的 a, p 下面的
a 的 hover 样式各要怎麽设定:
#header h1 {
font-size: 26
font-weight:
#header p {
font-size: 12
#header p a {
text-decoration:
#header p a:hover {
border-width: 1
这样的写法虽然很好理解,但要对于编写的人或是要修改的时候,就不是那麽方便了,因为你要改一下 header ,相关的样式可能散佈在
CSS 档的好几个地方。但在 Less 里面,我们可以有更好的做法:
font-size: 26
font-weight:
font-size: 12
text-decoration:
&:hover{border-width: 1}
通常在设计 button 或是 border
的样式的时候,我们常常会需要一个跟原本差不多的颜色。可能是亮一点点、暗一点点、或是鲜艳一点点(例如:当做 button
一般的颜色、hover 上去的颜色, 点下去的颜色)。而这样的东西,传统上我们是用 RGB 在调色盘上设好再设到 CSS
里,但如果你对 HSB (色相、明亮度、饱和度)有那麽一点直觉的话,Less 里面也可以让你直接用 function
来设定,而输出来的 css,就会自动帮你算好相对应的 RGB 。例如:
@base-color: #111;
@red: #842210;
color: @base-color + #003300;
border-color: desaturate(@red, 10%);
下面是转出来的 CSS:
color: #114411;
border-color: #7d2717;
模式匹配和导引表达式
有些情况下,我们想根据传入的参数来改变混合的默认呈现,比如下面这个例子:
.mixin (dark, @color) {
& color: darken(@color, 10%);
.mixin (light, @color) {
& color: lighten(@color, 10%);
.mixin (@_, @color) {
& display:
运用到class上:
& .mixin(light, #888);
下面是转出来的 CSS:
& color: #a2a2a2;
& display:
具体实现如下:
第一个混合定义并未被匹配,因为它只接受dark做为首参
第二个混合定义被成功匹配,因为它只接受light
第三个混合定义被成功匹配,因为它接受任意值
只有被匹配的混合才会被使用。变量可以匹配任意的传入值,而变量以外的固定值就仅仅匹配与其相等的传入值。
当我们想根据表达式进行匹配,而非根据值和参数匹配时,导引就显得非常有用。
为了尽可能地保留CSS的可声明性,LESS通过导引混合而非if/else语句来实现条件判断,因为前者已在@media
query特性中被定义。
以此例做为开始:
.mixin (@a) when (lightness(@a) &= 50%) {
& background-color:
.mixin (@a) when (lightness(@a) & 50%) {
& background-color:
.mixin (@a) {
& color: @a;
when关键字用以定义一个导引序列(此例只有一个导引)。接下来我们运行下列代码:
.class1 { .mixin(#ddd) }
.class2 { .mixin(#555) }
下面是转出来的 CSS:
& background-color:
& color: #
& background-color:
& color: #555;
Color 函数
Less 里面提供的 functions 还包括:
lighten(@color, 10%); // return a color which is 10% *lighter* than
darken(@color, 10%); // return a color which is 10% *darker* than
saturate(@color, 10%); // return a color 10% *more* saturated than
desaturate(@color, 10%); // return a color 10% *less* saturated
than @color
fadein(@color, 10%); // return a color 10% *less* transparent than
fadeout(@color, 10%); // return a color 10% *more* transparent than
spin(@color, 10); // return a color with a 10 degree larger in hue
than @color
spin(@color, -10); // return a color with a 10 degree smaller hue
than @color
Less 的编译方法
要把 Less 编译成 CSS 两种方法,一种是直接在 HTML里面 inlcude 一个
less.js&文档,然后就可以直接把 less&文档
include 进来。另一种是在制作 HTML 的时候,就先把 .less&文档预编译成
css&文档。建议用第二种方式,一方面可以让没有 js
的人也可以使用,另一方面效率上也会比较好。
第一种方式:
先在 HTML 里面 include less&文档
再把下面这个 script 放在
第二种方式:
如果您是 developer,您可以在 command line 直接安装 node.js + less (请参考这篇安装
node.js + less 的详细教学),并在 command line 执行:
lessc styles.less & styles.css
如果您是 designer 或是对 command line 不是那麽熟,可以考虑使用下面这个工具:
这个工具相当地方便,可以设定:
1.要去哪里找 less 档
2.要将编译(compile)好的 css 放在哪里,
3.多久自动编译一次
4.要不要自动帮 CSS 做压缩 (minified CSS)
5.检视编译有没有什麽问题
Less 的参考网址
有很详细的 Less 介绍。
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。通过bootstrap来学习less_Bootstrap_何问起
您的位置: -
通过bootstrap来学习less
  很早之前就听说过less了,但是一直拖着没去学习。最近抽空看了less,其实语法很简单,看一遍基本就知道怎么用了。平时自己写页面用less的话,感觉是方便了些,但是难道less的好处就只是这样?
  刚好最近也在学习bootstrap,发现其源文件就是用less写的,看了之后,我才深深体会的less的好处与强大,对less也有了更深一层的理解。
1、Less是什么?
  LESS CSS是一种动态样式语言,属于CSS预处理语言的一种,它使用类似CSS的语法,为CSS的赋予了动态语言的特性,如变量、继承、运算、函数等,更方便CSS的编写和维护。
  有些人可能没有接触过less,那我们就先可以简单的看看less的一些特性。
2、语言特性快速预览:
变量允许我们单独定义一系列通用的样式,然后在需要的时候去调用。所以在做全局样式调整的时候我们可能只需要修改几行代码就可以了。
LESS源码:
@color: #4D926F;
color: @color;
color: @color;
编译后的CSS:
color: #4D926F;
color: #4D926F;
混合(Mixins)
混合可以将一个定义好的class A轻松的引入到另一个class B中,从而简单实现class B继承class A中的所有属性。我们还可以带参数地调用,就像使用函数一样。
LESS源码:
.rounded-corners (@radius: 5px) {
-webkit-border-radius: @radius;
-moz-border-radius: @radius;
-ms-border-radius: @radius;
-o-border-radius: @radius;
border-radius: @radius;
.rounded-corners(10px);
编译后的CSS:
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
-ms-border-radius: 5px;
-o-border-radius: 5px;
border-radius: 5px;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
-ms-border-radius: 10px;
-o-border-radius: 10px;
border-radius: 10px;
我们可以在一个选择器中嵌套另一个选择器来实现继承,这样很大程度减少了代码量,并且代码看起来更加的清晰。
LESS源码:
font-size: 26px;
font-weight: bold;
font-size: 12px;
text-decoration: none;
border-width: 1px
编译后的CSS:
#header h1 {
font-size: 26px;
font-weight: bold;
#header p {
font-size: 12px;
#header p a {
text-decoration: none;
#header p a:hover {
border-width: 1px;
函数和运算
运算提供了加,减,乘,除操作;我们可以做属性值和颜色的运算,这样就可以实现属性值之间的复杂关系。LESS中的函数一一映射了JavaScript代码,如果你愿意的话可以操作属性值。
LESS源码:
@the-border: 1
@base-color: #111;
color: (@base-color * 3);
border-left: @the-border;
border-right: (@the-border * 2);
color: (@base-color + #003300);
border-color: desaturate(@red, 10%);
编译后的CSS:
color: #333;
border-left: 1px;
border-right: 2px;
color: #114411;
border-color: #7d2717;
  想具体学习less,可以访问何问起
3、bootstrap中less的使用
  下载 Bootstrap,解压缩文件。Bootstrap 的 Less 组件位于less目录下,其中包含至少20多个less文件,那为什么要分成这么多个呢?主要是方便开发,后期也便于维护,另外就是便于用户修改样式。
  开发人员在编写样式的时候,首先对页面的元素和作用效果进行分离,比如form,button,responsive,tables等等。然后分别编写,虽然是独立编写,但是有些样式是全局要用的,比如提醒的颜色,页面的背景色都是同一种。但是less文件很可能是多个人同时编写的,那怎么来确保样式的统一呢。这时候,less的作用就显现出来了。
  我们可以看看 variables.less 文件里的内容,下面节选了一部分:
// -------------------------
@grayDarker:
@grayDark:
@grayLight:
@grayLighter:
.........省略部分.....................
// Typography
// -------------------------
@sansFontFamily:
"Helvetica Neue", Helvetica, Arial, sans-
@serifFontFamily:
Georgia, "Times New Roman", Times,
@monoFontFamily:
Monaco, Menlo, Consolas, "Courier New",
@baseFontSize:
@baseFontFamily:
@sansFontF
@baseLineHeight:
@altFontFamily:
@serifFontF
@headingsFontFamily: // empty to use BS default, @baseFontFamily
@headingsFontWeight:
// instead of browser default, bold
@headingsColor: // empty to use BS default, @textColor
从上面可以看出,开发人员已经为一些常用的样式变成变量的形式。并且每一个变量的名字都很具体,只要一看就知道这是要设置什么。那具体是怎样用的呢?我们来看看buttons.less文件,同样是节选部分:
// Base styles
// --------------------------------------------------
display: inline-block;
.ie7-inline-block();
padding: 4px 12px;
margin-bottom: 0; // For input.btn
font-size: @baseFontSize;
line-height: @baseLineHeight;
text-align: center;
vertical-align: middle;
cursor: pointer;
.buttonBackground(@btnBackground, @btnBackgroundHighlight, @grayDark, 0 1px 1px rgba(255,255,255,.75));
border: 1px solid @btnBorder;
*border: 0; // Remove the border to prevent IE7's black border on input:focus
border-bottom-color: darken(@btnBorder, 10%);
.border-radius(@baseBorderRadius);
.ie7-restore-left-whitespace(); // Give IE7 some love
.box-shadow(~"inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05)");
怎么样,是不是很方便。妈妈再也不用担心我傻傻写错样式了。上面只是列举了了变量这一特性是使用,当然你还可以在其他文件上发现其他特性的使用。
4、合并编译less文件
文件都写好了,那怎么把它变成bootstrap.css呢。这里有个文件很重要,那就是bootstrap.less。最后只需要编译该文件就可以得到css文件了。我们来看看里面到底写了啥:
// Core variables and mixins
@import "variables.less"; // Modify this for custom colors, font-sizes, etc
@import "mixins.less";
// CSS Reset
@import "reset.less";
// Grid system and page structure
@import "scaffolding.less";
@import "grid.less";
@import "layouts.less";
// Base CSS
@import "type.less";
@import "code.less";
@import "forms.less";
@import "tables.less";
// Components: common
@import "sprites.less";
@import "dropdowns.less";
@import "wells.less";
@import "component-animations.less";
@import "close.less";
// Components: Buttons & Alerts
@import "buttons.less";
@import "button-groups.less";
@import "alerts.less"; // Note: alerts share common CSS with buttons and thus have styles in buttons.less
// Components: Nav
@import "navs.less";
@import "navbar.less";
@import "breadcrumbs.less";
@import "pagination.less";
@import "pager.less";
// Components: Popovers
@import "modals.less";
@import "tooltip.less";
@import "popovers.less";
// Components: Misc
@import "thumbnails.less";
@import "media.less";
@import "labels-badges.less";
@import "progress-bars.less";
@import "accordion.less";
@import "carousel.less";
@import "hero-unit.less";
// Utility classes
@import "utilities.less"; // Has to be last to override when necessary
  bootstrap.less作用是将其他less文件全部引入,但是引入的顺序还是有要求的。比如先引入 variables.less 和 mixins.less,是因为后面的less文件用到的less特性都是来自于这两个文件的,如果不先引入,就会出现编译错误的问题。然后再引入 reset.less 重置原有的样式。接着引入网格系统的相关文件,这是整个网格系统建立的关键所在。然后引入一些公用的组件,特定组件,最后就是一些无家可归但是比较有用的样式样式文件:utilities.less。
最后要做的就是编译bootstrap.less生成bootstrap.css文件。
如果你用的编辑器是 sublime text 安装less2css插件,使用需要nodejs环境,还有一个less的插件(这个你在使用的时候会提醒你缺少某个插件,然后安装就可以了)。
用gulp工具,参考何问起
  通过对bootstrap源码文件的分析,既了解到了less的作用,也明白预处理器流行的原因。其中有很多思想是值得我们学习的。比如编写一个样式框架要考虑哪些因素,如何分工合作等等。
  如果你写的页面,样式比较少,不推荐使用less,有点麻烦。当然如果你配置好相关环境了(比如工作中使用gulp或webpack来实现自动化)也就不用在乎了。
  如果你要写的样式比较多,推荐使用less。
  另外bootstrap官网提供样式定制,如果变动比较小的话,推荐直接修改bootstrap源文件,重新编译就好。ASP.NET MVC4 App fails to compile Bootstrap.LESS on production while it works on dev [ASP.NET应用程序编译失败mvc4 bootstrap.less生产而研究开发] - 问题-字节技术
ASP.NET MVC4 App fails to compile Bootstrap.LESS on production while it works on dev
ASP.NET应用程序编译失败mvc4 bootstrap.less生产而研究开发
问题 (Question)
I feel a Little stuck right now. First I used nuget to
install-package Bootstrap.less
as well as
install-package dotless
Then, as shown in
in asp.net mvc, I created a LessTransform-Class. I set up 2 nearly empty .less files and created a new bundle packaging them...
var lessBundle = new Bundle("~/MyLess").IncludeDirectory("~/Content/MyLess", "*.less", true);
lessBundle.Transforms.Add(new LessTransformer());
lessBundle.Transforms.Add(new CssMinify());
bundles.Add(lessBundle);
That worked well. Then I added a new StyleBundle to the main bootstrap.less file (which basically uses @import to include all the other .less files that bootstrap.less ships)...
bundles.Add(new StyleBundle("~/Bootstrap").Include("~/Content/Bootstrap/less/bootstrap.less"));
and a ScriptBundle to the bootstrap JavaScripts...
bundles.Add(new ScriptBundle("~/bundles/Bootstrap").Include("~/Scripts/bootstrap/js/bootstrap-*"));
to include all shipped bootstrap-*.js files and TADAA everything worked fine. The CSS got compiled including all imported JavaScript files were properly loaded.
But ... all that only worked for development mode with
&compilation debug="true" targetFramework="4.5"/&
As soon as I disable debug to see if the bundling into one file and the minification works properly I encounter the Problem.
The bundling process seems to fail to import all those .less files imported into bootstrap.less
/* Minification failed. Returning unminified contents.
(11,1): run-time error CSS1019: Unexpected token, found '/'
(11,2): run-time error CSS1019: Unexpected token, found '/'
(12,1): run-time error CSS1031: Expected selector, found '@import'
(12,1): run-time error CSS1025: Expected comma or open brace, found '@import'
(12,27): run-time error CSS1019: Unexpected token, found '/'
(12,28): run-time error CSS1019: Unexpected token, found '/'
... here go many many lines like these
(60,25): run-time error CSS1019: Unexpected token, found ';'
(62,1): run-time error CSS1019: Unexpected token, found '/'
(62,2): run-time error CSS1019: Unexpected token, found '/'
(63,1): run-time error CSS1031: Expected selector, found '@import'
(63,1): run-time error CSS1025: Expected comma or open brace, found '@import'
(63,27): run-time error CSS1019: Unexpected token, found '/'
(63,28): run-time error CSS1019: Unexpected token, found '/'
: run-time error CSS1067: Unexpected end of file encountered
* Bootstrap v2.3.1
* Copyright 2012 Twitter, Inc
* Licensed under the Apache License v2.0
* http://www.apache.org/licenses/LICENSE-2.0
* Designed and built with all the love in the world @twitter by @mdo and @fat.
// Core variables and mixins
@import "variables.less"; // Modify this for custom colors, font-sizes, etc
@import "mixins.less";
... and the rest of the original bootstrap.less... no style definitions
having a look at the minified bootstrap.javascript bundle also boggles me. in dev there was no Problem after loading the page, now after the bootstrap.javascript was bundled and minified in Google the JavaScript console states
Uncaught TypeError: Cannot read property 'Constructor' of undefined
I have had a look at several Topics that seemed closely related to my Problem, and I tried a few things, but so far without success.
Many thanks in advance to anyone who could shed some light into my Situation and who would point out what I am missing or doing wrong. Best regards, Ingo
我觉得有点困现在。首先我用NuGet来
bootstrap.less安装包以及
dotless安装包然后,如图所示在ASP.NET MVC,我创建了一个lesstransform类。我设置了2个几乎空了。小文件并创建一个新的捆绑包装…
var lessBundle = new Bundle("~/MyLess").IncludeDirectory("~/Content/MyLess", "*.less", true);
lessBundle.Transforms.Add(new LessTransformer());
lessBundle.Transforms.Add(new CssMinify());
bundles.Add(lessBundle);
这工作得很好。然后我到主bootstrap.less文件添加了一个新的stylebundle(基本上使用@import包含所有其他。少文件bootstrap.less船舶)…
bundles.Add(new StyleBundle("~/Bootstrap").Include("~/Content/Bootstrap/less/bootstrap.less"));
并以引导javascripts scriptbundle…
bundles.Add(new ScriptBundle("~/bundles/Bootstrap").Include("~/Scripts/bootstrap/js/bootstrap-*"));
包括所有运引导*。JS文件和tadaa一切都很正常。的CSS有编制包括所有进口的JavaScript文件被正确加载。但…所有工作的发展模式
&compilation debug="true" targetFramework="4.5"/&
当我关闭调试看看捆绑成一个文件,缩小工作正常,我遇到的问题。捆绑的过程似乎无法导入这些文件导入到bootstrap.less少。/* Minification failed. Returning unminified contents.
(11,1): run-time error CSS1019: Unexpected token, found '/'
(11,2): run-time error CSS1019: Unexpected token, found '/'
(12,1): run-time error CSS1031: Expected selector, found '@import'
(12,1): run-time error CSS1025: Expected comma or open brace, found '@import'
(12,27): run-time error CSS1019: Unexpected token, found '/'
(12,28): run-time error CSS1019: Unexpected token, found '/'
... here go many many lines like these
(60,25): run-time error CSS1019: Unexpected token, found ';'
(62,1): run-time error CSS1019: Unexpected token, found '/'
(62,2): run-time error CSS1019: Unexpected token, found '/'
(63,1): run-time error CSS1031: Expected selector, found '@import'
(63,1): run-time error CSS1025: Expected comma or open brace, found '@import'
(63,27): run-time error CSS1019: Unexpected token, found '/'
(63,28): run-time error CSS1019: Unexpected token, found '/'
: run-time error CSS1067: Unexpected end of file encountered
* Bootstrap v2.3.1
* Copyright 2012 Twitter, Inc
* Licensed under the Apache License v2.0
* http://www.apache.org/licenses/LICENSE-2.0
* Designed and built with all the love in the world @twitter by @mdo and @fat.
// Core variables and mixins
@import "variables.less"; // Modify this for custom colors, font-sizes, etc
@import "mixins.less";
... and the rest of the original bootstrap.less... no style definitions
在后一看还让我bootstrap.javascript束。在开发是没有任何问题的加载页面后,后被压缩在谷歌bootstrap.javascript JavaScript控制台状态Uncaught TypeError: Cannot read property 'Constructor' of undefined
我有几个主题,似乎我的问题密切相关的一看,我尝试了一些东西,但到目前为止没有成功。提前谢谢谁能揭示一些我的情况,谁能指出我失踪或做错事。诚挚的问候,英格
最佳答案 (Best Answer)
If you want to use bootstrap as less-files and in addition want to stop worrying about bundling and minification on your development machine as well as on your production machine, you might consider using the following approach.
Note: you don't need all this if you only play around with Less-Files while DEBUG But as soon as you want your application to go live on a production server like Windows Azure, and still want to just modify your less files without having to take care about the bundling and minification procedures... well... then this approach will work
So in order to solve the problem I felt a little stuck in, I had to approach the problem differently and had to modify (see Modification 2 further down the post) the "BundleSource" I thought I'd like to
SO DONT FORGET TO READ THE 2nd Modification/Warning close to the bottom of this answer!
MODIFICATION 1)
So the first and bigger part of the job is to get the bundling of the bootstrap-less files working. In order to do that I took the liberty to fork a piece of code I found in the web that (if you only need one less-file bundle) itself solves my problem... unless you might want to use or be able to use multiple less-bundles with several base directories... So that is where I actually found the approach that helped me a lot ...
... wherefore I award many thanks to
"Using ASP.NET bundling and minification with LESS files" which I accidently and gladly stumbled over.
Like me he tried to use the LessMinify.cs that Scott Hanselman was showing in his speeches to work with 1 LESS-file instead of just bundling every single file in 1 directory full of LESS-files.
But he had to extend the whole bundling procedure slightly as he shows in his Blog-Entry. That way the solution he proposes can bundle 1 less file that uses imports to load other less files. But as he statically implements the path that is added to the source directory in which to find the
less files... whichever less bundle you define has to pick a less file in the same directory...
That is where I took the liberty to extend his solution a bit further. I created a file LessBundling.cs with the following content:
using dotless.Core.
using dotless.Core.I
using MvcApplication2.U
using System.Collections.G
using System.IO;
using System.L
using pilerS
using System.W
using System.Web.H
using System.Web.O
namespace MvcApplication2.Extensions
// create Less-Minifier (use Type to define source directory of less files [see below at BootstrapFileReader])
public class LessMinify&TFileReader& : CssMinify
where TFileReader : IFileReader
public LessMinify() {}
public override void Process(BundleContext context, BundleResponse response)
var config = new DotlessConfiguration()
MinifyOutput = true,
ImportAllFilesAsLess = true,
CacheEnabled = false,
LessSource = typeof(TFileReader)
response.Content = dotless.Core.Less.Parse(response.Content, config);
base.Process(context, response);
// create a LessStyleBundler to allow initializing LessBundle with a single less file that uses imports
public class LessStyleBundle&TFileReader& : Bundle
where TFileReader : IFileReader
public LessStyleBundle(string virtualPath)
: base(virtualPath, new LessMinify&TFileReader&()) {}
public LessStyleBundle(string virtualPath, string cdnPath)
: base(virtualPath, cdnPath, new LessMinify&TFileReader&()) { }
// create abstract VirtualFileReader from dotless-IFileReader as a Base for localized
internal abstract class VirtualFileReader : IFileReader
public byte[] GetBinaryFileContents(string fileName)
fileName = GetFullPath(fileName);
return File.ReadAllBytes(fileName);
public string GetFileContents(string fileName)
fileName = GetFullPath(fileName);
return File.ReadAllText(fileName);
public bool DoesFileExist(string fileName)
fileName = GetFullPath(fileName);
return File.Exists(fileName);
public string GetFullPath(string path)
HostingEnvironment.MapPath(SourceDirectory + path);
public abstract string SourceDirectory {}
// implement to return Path to location of less files
// e. g. return "~/Content/bootstrap/less/";
// create BootstrapFileReader overwriting the Path where to find the Bootstrap-Less-Files
internal sealed class BootstrapFileReader : VirtualFileReader
public override string SourceDirectory
get { return "~/Content/bootstrap/less/"; }
So what does this actually do?
LessMinify extends the CssMinify class and therefore brings everything needed to minify css files
The important difference to "usual" bundling is that you create a new Dotless-Configuration with the LessSource defined as typeof(TFileReader) ...
By using &TFileReader& you can define a class that will contain the source directory in which the bundler/minifier will look for the less files to be taken into account
LessStyleBundle extends Bundle and therefore brings everything needed to bundle the files
In this class I again use TFileReader as this is where the LessMinify(er) will be instantiated
VirtualFileReader implements IFileReader which is a dotless interface defining all methods required to parse less files and give information where to find files to be imported
In order to extend Kristof's solution to the problem I added the abstract property SourceDirectory... requiring me to also make the VirtualFileReader abstract class
Now with that setup you can create as many LessFileReaders as you want. You just have to extend the abstract VirtualFileReader as can be seen in
BootstrapFileReader extends VirtualFileReader
The only purpose of the BootstrapFileReader is to have a property-getter for the SourceDirectory in which the bundler/minifier will find the less files that are to be imported
Well in my case Bootstraps Less-Files where lying in ~/Content/bootstrap/less which should be the default location if you install the "twitter.bootstrap.less"-nugget.
If you'd have another directory in your application, which contained a less file which again has multiple imports you just create a new class extending VirtualFileReader and define the property-getter for the SourceDirectory to return the corresponding path
If you then want to use this Bundling method to actually bundle and minify less files in a production environment you just add the LessStyleBundle-instantion to the BundlerConfig.cs:
bundles.Add(new LessStyleBundle&BootstrapFileReader&("~/bundles/BootstrapCSS")
.Include("~/Content/bootstrap/less/bootstrap.less"));
and of course your _Layout.cshtml should also be aware of the readily prepared bundle
@Styles.Render("~/bundles/BootstrapCSS")
MODIFICATION 2)
now the minor Modification which I also had to add to get this working
In my first attempt to bundle bootstrap.less I used this
bundles.Add(new LessStyleBundle&BootstrapFileReader&("~/Content/BootstrapCSS")
.Include("~/Content/bootstrap/less/bootstrap.less"));
I thought I would use Content in the routes for CSS/Less and Bundles in the routes for Javascript.
But that does not work out of the box. ASP.net doesnt permit the creation of a Bundle that starts with ~/Content. You will get a 403 authorization failure. Therefore the easiest solution to that is to use ~/bundles instead:
bundles.Add(new LessStyleBundle&BootstrapFileReader&("~/bundles/BootstrapCSS")
.Include("~/Content/bootstrap/less/bootstrap.less"));
As there aren't many real solutions to this problem I hope this will help at least some of you if you plan to integrate twitter bootstrap into your asp.net mvc4 application.
best regards,
如果你想使用引导文件,除了不想再担心捆绑和缩小你的开发机以及您的生产机器,你可以考虑使用下面的方法。 注意:你不需要这一切如果你只玩小文件时启用了调试;但当你希望你的应用程序去生活在生产服务器上像Windows Azure,还想修改你的小文件而无需采取捆绑和缩小的程序护理…好…然后,这种方法将工作所以为了解决我觉得有点困在这个问题,我有不同的方法的问题,不得不修改(见修改2进一步下降后)“bundlesource“我想有。所以不要忘记读第二修改/警告接近这个答案的底部!修改1)所以工作的第一个大的部分是让捆绑引导少的档案工作。为了你,我冒昧的叉的一段代码,我在网上找到,(如果你只需要一个较小的文件包)本身解决了我的问题…除非你想使用或可以使用多个较小的束与基础目录…所以,我真的发现给了我很多帮助的方法… …所以我奖谢谢“使用ASP.NET捆绑缩少文件”,我不小心,绊倒。 像我,他想利用史葛Hanselman表明了自己的发言,而不是将每个文件在目录中的全部文件1少少了1个文件工作lessminify.cs。 但他不得不延长整个捆绑程序略为他对自己的博客。这样,他提出了能束少1,采用进口文件加载其他较少的文件。但当他静了,加上在源目录中找到不文件的路径…任何不把你定义在同一个目录中选择一个较小的文件…这就是我冒昧的向他解远一点。我创建了一个文件lessbundling.cs下列内容:using dotless.Core.
using dotless.Core.I
using MvcApplication2.U
using System.Collections.G
using System.IO;
using System.L
using pilerS
using System.W
using System.Web.H
using System.Web.O
namespace MvcApplication2.Extensions
// create Less-Minifier (use Type to define source directory of less files [see below at BootstrapFileReader])
public class LessMinify&TFileReader& : CssMinify
where TFileReader : IFileReader
public LessMinify() {}
public override void Process(BundleContext context, BundleResponse response)
var config = new DotlessConfiguration()
MinifyOutput = true,
ImportAllFilesAsLess = true,
CacheEnabled = false,
LessSource = typeof(TFileReader)
response.Content = dotless.Core.Less.Parse(response.Content, config);
base.Process(context, response);
// create a LessStyleBundler to allow initializing LessBundle with a single less file that uses imports
public class LessStyleBundle&TFileReader& : Bundle
where TFileReader : IFileReader
public LessStyleBundle(string virtualPath)
: base(virtualPath, new LessMinify&TFileReader&()) {}
public LessStyleBundle(string virtualPath, string cdnPath)
: base(virtualPath, cdnPath, new LessMinify&TFileReader&()) { }
// create abstract VirtualFileReader from dotless-IFileReader as a Base for localized
internal abstract class VirtualFileReader : IFileReader
public byte[] GetBinaryFileContents(string fileName)
fileName = GetFullPath(fileName);
return File.ReadAllBytes(fileName);
public string GetFileContents(string fileName)
fileName = GetFullPath(fileName);
return File.ReadAllText(fileName);
public bool DoesFileExist(string fileName)
fileName = GetFullPath(fileName);
return File.Exists(fileName);
public string GetFullPath(string path)
HostingEnvironment.MapPath(SourceDirectory + path);
public abstract string SourceDirectory {}
// implement to return Path to location of less files
// e. g. return "~/Content/bootstrap/less/";
// create BootstrapFileReader overwriting the Path where to find the Bootstrap-Less-Files
internal sealed class BootstrapFileReader : VirtualFileReader
public override string SourceDirectory
get { return "~/Content/bootstrap/less/"; }
这究竟是做什么的?lessminify延伸cssminify类和因此需要缩小CSS文件的一切重要的区别是“正常”的捆绑,你创建一个新的dotless配置与lesssource定义为typeof(tfilereader)… you can define a class that will contain the source directory in which the bundler/minifier will look for the less files to be taken into account"&利用& tfilereader&你可以定义一个类将包含源目录中的打包机/缩小镜会少文件加以考虑lessstylebundle延伸束和因此带来所需的一切捆绑文件这节课我再次使用tfilereader因为这就是lessminify(ER)将被实例化virtualfilereader ifilereader是实现接口定义的所有方法dotless需要解析少文件和提供信息在哪里可以找到要导入的文件为了延长克里斯托夫的解决我添加了抽象属性sourcedirectory问题…要求我也使virtualfilereader抽象类现在,你可以创建许多lessfilereaders设置为你想要的。你不得不延长摘要virtualfilereader可以看出bootstrapfilereader virtualfilereader延伸bootstrapfilereader的唯一目的是为其打捆机sourcedirectory /缩小镜会发现较少的文件,要输入属性getter在我的情况下白手起家少文件的地方躺在~ /内容/引导/不应该如果你安装“推特是默认位置。引导。少”金块。如果你想在你的应用程序有一个目录,其中包含一个较小的文件又有多个进口,你创建一个新类的扩展和定义为virtualfilereader sourcedirectory返回相应的路径属性getter如果你想用这种捆绑方法实际束、缩小减少文件在生产环境中你只是添加到bundlerconfig.cs lessstylebundle instantion:bundles.Add(new LessStyleBundle&BootstrapFileReader&("~/bundles/BootstrapCSS")
.Include("~/Content/bootstrap/less/bootstrap.less"));
当然,你也应该知道_layout.cshtml随时准备束@Styles.Render("~/bundles/BootstrapCSS")
修改2)现在的小修改,我也加入到这个工作在我第一次尝试束bootstrap.less我用这个bundles.Add(new LessStyleBundle&BootstrapFileReader&("~/Content/BootstrapCSS")
.Include("~/Content/bootstrap/less/bootstrap.less"));
我想我会在路线使用内容的CSS和JavaScript /少的路线束。但这并不解决的盒子。ASP.NET也允许一束开始创作~ /内容。你将得到403的授权失败。因此最简单的解决方法是使用~ /束而不是:bundles.Add(new LessStyleBundle&BootstrapFileReader&("~/bundles/BootstrapCSS")
.Include("~/Content/bootstrap/less/bootstrap.less"));
没有多少真正的解决这个问题,我希望这将有助于至少一些你如果你计划将引导到你的ASP.NET应用推特mvc4。诚挚的问候,
答案 (Answer) 2
I was having the same issue today, I found a work around but I'd like a better solution as well. I was also trying to use dotless and a custom transform like what you have.
Workaround:
Pre-build event:
"$(SolutionDir)packages\dotless.1.3.1.0\piler.exe" "$(ProjectDir)Content\less\bootstrap.less"
That will create a bootstrap.css file which you can then include as regular CSS instead of LESS.
This solution isn't ideal, as you'd have to update the build event each time you update dotless, and having the bundle handle it is cleaner as well.
我今天有同样的问题,我找到了一份工作但我想一个更好的解决方案和。我也试图用dotless和自定义转换像你。解决方法:预生成事件:"$(SolutionDir)packages\dotless.1.3.1.0\piler.exe" "$(ProjectDir)Content\less\bootstrap.less"
这将创建一个bootstrap.css文件可以包括定期CSS而不是LESS。这个解决方案并不理想,你会有更新的生成事件每次更新dotless,具有束处理它是清洁和。
答案 (Answer) 3
I really, really recommend installing
It will generate a css-file AND a minified css-file from your .less and you can reference the css instead. It will automatically update the css everytime you make a change to your .less so there is no need to remember any pre-build steps or anything...
When installing WebEssentials you'll also get other sweet features like preview of CoffeeScript, TypeScript and LESS. JSHint, automatic minification and lots and lots more "goodies"!
我真的,真的建议安装而不是。这将产生一个CSS文件和一个缩小的CSS文件从您的。不,你可以参考CSS代替。它会自动更新CSS每次你做出改变。不这样就不需要记住任何预生成步骤或什么的…安装时,你也会得到其他甜webessentials特征预览coffeescript,打字少。jshint自动缩小,以及更多的“礼物”!
答案 (Answer) 4
I've modified Ingo workaround to get rid of custom classes for each directory.
Also, I've added proper exception output (because otherwise all exceptions was silent and you just got empty less file in case of error).
public class LessTransform : IItemTransform
[ThreadStatic]
internal static string CurrentParsedFileD
public string Process (string includedVirtualPath, string input)
CurrentParsedFileDirectory = Path.GetDirectoryName (includedVirtualPath);
var config = new DotlessConfiguration
MinifyOutput = false,
CacheEnabled = false,
MapPathsToWeb = true,
ImportAllFilesAsLess = true,
LessSource = typeof (VirtualFileReader),
Logger = typeof (ThrowExceptionLogger)
return Less.Parse (input, config);
internal class VirtualFileReader : IFileReader
public bool UseCacheDependencies
public byte[] GetBinaryFileContents (string fileName)
return File.ReadAllBytes (GetFullPath (fileName));
public string GetFileContents (string fileName)
return File.ReadAllText (GetFullPath (fileName));
public bool DoesFileExist (string fileName)
return File.Exists (GetFullPath (fileName));
public string GetFullPath (string path)
if (string.IsNullOrEmpty (path))
return string.E
return HostingEnvironment.MapPath (path[0] != '~' && path[0] != '/'
? bine (LessTransform.CurrentParsedFileDirectory, path)
public class ThrowExceptionLogger : Logger
public ThrowExceptionLogger (LogLevel level) : base (level)
protected override void Log (string message)
if (string.IsNullOrEmpty (message))
if (message.Length & 100)
message = message.Substring (0, 100) + "...";
throw new LessTransformException (message);
[Serializable]
public sealed class LessTransformException : Exception
public LessTransformException (string message) : base (message)
bundles.Add (new StyleBundle ("~/styles-bundle/common")
.Include ("~/content/bootstrap/bootstrap.less", new LessTransform ()));
我已经修改了英格以摆脱自定义类的每个目录。我添加适当也,异常输出(因为所有的异常寂静,你的文件的情况下就空了更少的错误。public class LessTransform : IItemTransform
[ThreadStatic]
internal static string CurrentParsedFileD
public string Process (string includedVirtualPath, string input)
CurrentParsedFileDirectory = Path.GetDirectoryName (includedVirtualPath);
var config = new DotlessConfiguration
MinifyOutput = false,
CacheEnabled = false,
MapPathsToWeb = true,
ImportAllFilesAsLess = true,
LessSource = typeof (VirtualFileReader),
Logger = typeof (ThrowExceptionLogger)
return Less.Parse (input, config);
internal class VirtualFileReader : IFileReader
public bool UseCacheDependencies
public byte[] GetBinaryFileContents (string fileName)
return File.ReadAllBytes (GetFullPath (fileName));
public string GetFileContents (string fileName)
return File.ReadAllText (GetFullPath (fileName));
public bool DoesFileExist (string fileName)
return File.Exists (GetFullPath (fileName));
public string GetFullPath (string path)
if (string.IsNullOrEmpty (path))
return string.E
return HostingEnvironment.MapPath (path[0] != '~' && path[0] != '/'
? bine (LessTransform.CurrentParsedFileDirectory, path)
public class ThrowExceptionLogger : Logger
public ThrowExceptionLogger (LogLevel level) : base (level)
protected override void Log (string message)
if (string.IsNullOrEmpty (message))
if (message.Length & 100)
message = message.Substring (0, 100) + "...";
throw new LessTransformException (message);
[Serializable]
public sealed class LessTransformException : Exception
public LessTransformException (string message) : base (message)
使用:bundles.Add (new StyleBundle ("~/styles-bundle/common")
.Include ("~/content/bootstrap/bootstrap.less", new LessTransform ()));
本文翻译自StackoverFlow,英语好的童鞋可直接参考原文:

我要回帖

更多关于 bootstrap less 文件 的文章

 

随机推荐