Visual Studio: Customising Bootstrap at Build time
I've been using Bootstrap for a number of my personal projects over the past few months and I've frequently found myself customising its theme by either overriding CSS styles or using Bootstrap's customisation tool. The problem is of course that the former led to more CSS and the latter was time consuming.
Instead of repeating either of the aforementioned tasks I have now integrated the building of Bootstrap, along with my customisations, into the build process of my project. Saving a lot of time and producing less CSS. I have documented how I did it below...
Download Bootstrap's source
The easiest way of incorporating Bootstrap's source into a project is to download the source-code and put it in your project's directory. However as my project is versioned using git I chose to add it as a sub-module.
Installing a LESS compiler
Bootstrap is built using a dynamic style sheet language called less, which is compiled into CSS. There are a number of less compilers out there but the easiest one to acquire is the one used by Bootstrap's build process, called RECESS.
Downloading RECESS is super simple if node.js is installed. All one has to do is run "npm install" from within Bootstrap's directory and NPM will download and install RECESS for you - along with various over tools used in Bootstrap's own build process.
Integrate into the Visual Studio project
Add variables.less to the project
The preferred way of customising Bootstrap is through its variables.less file. This file holds the variables for styling Bootstrap's components.
In my ASP.NET MVC 4 project I copied the variables.less file into my project's Content directory and changed its Build Action property to None, in order to stop it being deployed.
It is this variables.less files that I customise and then use when compiling Bootstrap.
Create a batch script for automating the building
The batch script I created replaces Bootstrap's variables.less file with mine then executes a build process similar to Bootstrap's makefile build task - but with Windows command-line tools. It then reinstates the original variables.less file to stop git prompting me that the sub-module has local changes.
As I did with the variables.less file I also added the batch script my project - to the base directory this time - and set its Build Action property to None.
Although Bootstrap's build task minifies the resulting JS and CSS files this wasn't necessary for my project as I have access to Bundling, which does all that for me.
Call the batch file at pre-build time
Add the following to your project's pre-build script (making modifications to the paths where necessary).
call "$(ProjectDir)BuildBootstrap.bat" "$(SolutionDir)" "$(ProjectDir)"
Build your project
Don't forget to include the resulting files as part of your solution if you plan on publishing your project from Visual Studio.