如何在前端專案中引用bootstrap less?

世有因果知因求果發表於2015-04-01

  在基於bootstrap css框架的前端專案開發中,如果有grunt build系統,那麼工作流是:客製化less,在less中定義自己的

CSS,同時可以隨意引用bootstrap中預定義好的css類,一旦儲存檔案,grunt則開始重新構建,生成最後的生產檔案。問題是:

如何能夠在自己的客制less檔案中引入bootstrap的less變數或者mixin呢?

比如:我如何能夠實現在螢幕尺寸在@screen-md時,將所有的圖片隱藏呢?

對於這個場景,假設專案目錄結構如下:

> bower_components
  > bootstrap
  > font-awesome
  > requirejs
  ...
> css
  - project.css
  > less
    - project.less
    - variables.less

 

可行的辦法為:

1.在project.less中import bootstrap.less,font-awsome,以及自己定義的專案所需less檔案:

// Bootstrap framework
@import "../../bower_components/bootstrap/less/bootstrap.less";

// Font-awesome awesomeness
@import "../../bower_components/font-awesome/less/font-awesome.less";

// Project specific stuff
@import "variables.less";
@import "stuff.less";

2.在variables.less檔案中一方面定義自己的所需變數,另一方面可以覆蓋掉bootstrap的預置變數;

// Override Bootstrap variables
@font-family-sans-serif:  "Lucida Grande","Lucida Sans Unicode",Arial,sans-serif;
@btn-default-border: #bbb;
@brand-primary: #b02b2c;
@link-color: #08c;

// Override Font-Awesome variables (path relative to project.css position)
@fa-font-path: "../bower_components/font-awesome/fonts";

//Map Bootstrap variables to myproject specific names
@my-customname-float-breakpoint: @grid-float-breakpoint;
@theme-color: @brand-primary;

//Project specific variables
@my-favourite-color: rgb(228, 1, 1);

3.僅僅編譯project.less檔案,最後生成一個包羅永珍的巨大css檔案(注意這裡也包含font-awsome)

4.既然在project.less中已經引入了bootstrap.less,那麼在後面import的自創less檔案自然可以引用任何bootstrap less變數或mixin,比如:

// Hide all images at a viewport smaller than 992px (aka @screen-md)
@media (max-width: @screen-sm-max) {
    img {
        display: none;
    }
}

原文出處:

http://stackoverflow.com/questions/20246514/using-twitter-bootstrap-3-during-development

http://transmission.vehikl.com/using-bootstrap-as-a-semantic-mixin-library/

http://www.helloerik.com/bootstrap-3-less-workflow-tutorial

http://slicejack.com/bootstrap-with-less-workflow/

https://www.npmjs.com/package/grunt-include-bootstrap

http://stackoverflow.com/questions/12655034/how-to-use-bootstrap-and-less-and-keep-a-clean-project

相關文章