• 0

Guide to getting LESS working with Twitter Bootstrap in MVC 5


Question

What a pain in the ass to figure out when many of the other guides are for older versions or use dead projects.  I'm throwing this up in case anyone else wants to get LESS in MVC5.

 

What I'll be using:

Visual Studio 2013 Professional (Express versions probably work fine)

Web Essentials 2013 (A free extension, not required but nice to have)

Twitter Bootstrap (Just awesome)

 

So... LET THE FUN BEGIN

 

1.  Start with a new project then go to nuget and let's download what we need.  If you are unfamiliar with nuget, its an awesome package management service.

Go to Tools > Library Package Manager > Manage NuGet Packages for solution...

 

2.  Since Visual Studio 2013's release, there are already updates you can run on your project.

Click Updates and for the purpose of this guide, update:

> jQuery

> Microsoft ASP.NET Web Optimization Framework

> ANTLRv3

 

After this is done  Click Online on the left side then in the search box type "Bootstrap Less Source".  The current version is 3.0.2.

 

You'll see in the dependencies that LESS will also be installed. Install it.

 

Next, search for Bundle Transformer: LESS, Install this.

 

Finally, we need a javascript engine.  Bundle Transformer will give you a head up about this and give you two options.  Either MSIE or V8.  I'll be installing V8 because it sounds cool.

 

Search for V8 and the first one should be "JavaScript Engine Switcher for .Net: V8", install it.

 

3.  Associate V8 with Bundle Transformer (BT).

BT needs to know which engine to use so it can compile your LESS files.  So in your solution, scroll to the bottom and open "Web.Config".  If your config file looks like hell, Visual Studio has the best button of any IDE.  Click Edit > Advanced > Format Document.  SURPRISE! VS retabbed the structured XML!

 

To associate add the <less> block:

<bundleTransformer xmlns="http://tempuri.org/BundleTransformer.Configuration.xsd">
    <less useNativeMinification="false" ieCompat="true" strictMath="false" strictUnits="false" dumpLineNumbers="None">
      <jsEngine name="V8JsEngine" />
    </less>
    <core>
      <css>
        <minifiers>
          <add name="NullMinifier" type="BundleTransformer.Core.Minifiers.NullMinifier, BundleTransformer.Core" />
        </minifiers>
        <translators>

Save it.

 

4. Creating your bundles

Bundles are the new Jesus of the internet.  They simply make life easier.  For certain types like .js, MVC allows wildcards which is awesome.

 

Go to App_Start > BundleConfig.cs

 

First we need to type in our using statements so the file knows which libraries to use.

using System.Web.Optimization;
using BundleTransformer.Core.Builders;
using BundleTransformer.Core.Orderers;
using BundleTransformer.Core.Transformers;

In the BT documentation there is another way to build your bundles but for the purpose of this, I'll be doing it the long way.

 

Now everything inside the scope of RegisterBundles, delete (This is entirely optional.)

 

Now within the same scope, create new instances of variables.

            // Variables
            bundles.UseCdn = true;
            var nullBuilder = new NullBuilder();
            var cssTransformer = new CssTransformer();
            var jsTransformer = new JsTransformer();
            var nullOrderer = new NullOrderer();

Next, associating our scripts

            // JavaScript

            // jQuery
            var jquery = new Bundle("~/bundles/jquery").Include(
                "~/Scripts/jquery-{version}.js");
            jquery.Builder = nullBuilder;
            jquery.Transforms.Add(jsTransformer);
            jquery.Orderer = nullOrderer;

            bundles.Add(jquery);

            // Modernizr
            var modernizr = new Bundle("~/bundles/modernizr").Include(
                "~/Scripts/modernizr-2.6.2.js");
            modernizr.Builder = nullBuilder;
            modernizr.Transforms.Add(jsTransformer);
            modernizr.Orderer = nullOrderer;

            bundles.Add(modernizr);

            // Scripts
            var js = new Bundle("~/bundles/js").Include(
                "~/Scripts/bootstrap.min.js",
                "~/Scripts/myScripts.js");
            js.Builder = nullBuilder;
            js.Transforms.Add(jsTransformer);
            js.Orderer = nullOrderer;

            bundles.Add(js);

            // POST: Validation
            var jqueryVal = new Bundle("~/bundles/jqueryval").Include(
                "~/Scripts/jquery.validate.unobtrusive.min.js",
                "~/Scripts/jquery.validate.min.js");
            jqueryVal.Builder = nullBuilder;
            jqueryVal.Transforms.Add(jsTransformer);
            jqueryVal.Orderer = nullOrderer;

            bundles.Add(jqueryVal);

jQuery should always go first.  Next Styles.  What's nice about this is at compile time it automatically minifies the CSS.

            // Styles
            var css = new Bundle("~/bundles/css").Include(
                "~/Content/bootstrap/bootstrap.less");
            css.Builder = nullBuilder;
            css.Transforms.Add(cssTransformer);
            css.Transforms.Add(new CssMinify());
            css.Orderer = nullOrderer;

            bundles.Add(css);

Finally, we tell the bundles to optimize.

            BundleTable.EnableOptimizations = true;

Ok so let's run our project quick!

 

OH GOD WHAT HAPPENED?!!!  ohhh the humanity!  The styles are dead!!  ohhhhhh!!!!!!!!!

 

Hang on!  On to step 5!

 

5. Associate our bundles with the layout

Go to Views > Shared > _Layout.cshtml

 

In the header add:

    <!-- styles -->
    @Styles.Render("~/bundles/css")
    <!-- /styles -->
    @Scripts.Render("~/bundles/modernizr")

and down on the bottom of the body add:


    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/js")

Compile the project again and whaddya know LESS WORKS!  Now you can configure your variables using LESS and save time!

 

KNOWN ISSUES:

 

Google is not happy with query strings.

2 Bad requests atm, tomorrow may have update.

Modernizr is not production version, get that at their website.

 

FINALLY:

If anyone knows some better solutions or fixes.  DO TELL!

7 answers to this question

Recommended Posts

  • 0

I thought less was the 'opposite of more':

Less  is  a program similar to more (1), but it has many more features.  Less does not have to read the entire input file before starting, so with large input files it starts up faster than text editors like vi (1).  Less uses termcap (or terminfo on some systems), so  it  can run  on  a  variety  of  terminals.  There is even limited support for hardcopy terminals.  (On a hardcopy terminal, lines which should be printed at the top of the screen are prefixed with a caret.)

Commands are based on both more and vi.  Commands may be preceded by a decimal number, called N in the descriptions below.  The number  is used by some commands, as indicated.
  • 0

Hello, Kalint!

Thanks for a great guide! But there is one problem: is not recommended to use the `CssMinify` and `JsMinify` classes together with a Bundle Transformer. I will not explain why it should not do, because I have written about this in the documentation. As most simple solution to this problem I recommend to install the BundleTransformer.MicrosoftAjax package.

  • 0
  On 07/12/2013 at 11:49, Taritsyn said:

Hello, Kalint!

Thanks for a great guide! But there is one problem: is not recommended to use the `CssMinify` and `JsMinify` classes together with a Bundle Transformer. I will not explain why it should not do, because I have written about this in the documentation. As most simple solution to this problem I recommend to install the BundleTransformer.MicrosoftAjax package.

Hm... I will look into this!

This topic is now closed to further replies.
  • Posts

    • There are too many people doing nothing and just cruising at MS because of how the previous culture was (rest and vest).
    • AMD Ryzen AM4 16-core 5900XT processor has never been priced cheaper by Sayan Sen While AMD's newest processor platform with DDR5 and PCIe 5.0 goodness is AM5, the preceding Socket AM4 continues to be a great option for gamers shopping on a lower budget. One of the most powerful AM4 desktop chips, the 16-core Ryzen 9 5900XT, is currently priced at the lowest ever at just $230 (purchase links down below). The Ryzen 7 5900XT is based on the Zen 3 architecture supports DDR4, PCIe Gen4, and offers very good performance in both gaming and productivity. While users may not expect the same level of gaming throughput or latency improvement as the 5800X3D, it is certainly possible that titles that utilize more than 16 threads will favor the 5900XT over the 5800X3D. And the 5900XT has plenty of L3 cache as well at 64 MB. So while not 3D stacked V-cache, it should still be a decent gaming chip. And all that cache as well as cores/threads will be excellent for non-gaming tasks of course. The CPU has a base clock of 3.3 GHz and boosts up to 4.8. It has a TDP of 105 watts so the available power envelope certainly helps with that. It can tolerate temperatures of up to 90 °C and there is no boxed cooler with it. So you need an aftermarket one, ideally a 280 mm or 360 mm AIO liquid cooler or an excellent air cooler. Also since this is a 16-core 105-watt chip, make sure to run it on an AM4 board that has good quality VRM and cooling with lots of power (ideally an X570 motherboard). Another consideration is that it does not have integrated graphics so you need a separate dedicated GPU for display out. Get the AMD Ryzen 9 5900XT at the links below: AMD Ryzen 9 5900XT - No Integrated Graphics Desktop CPU Processor - 100-100001581WOF: $229.99 (Amazon US) || : $279.00 (Newegg US + Corsair 32GB DDR4-3200 RAM) This Amazon deal is US-specific and not available in other regions unless specified. If you don't like it or want to look at more options, check out the Amazon US deals page here. Get Prime (SNAP), Prime Video, Audible Plus or Kindle / Music Unlimited. Free for 30 days. As an Amazon Associate, we earn from qualifying purchases.
    • OnlyOffice 9.0.0 by Razvan Serea OnlyOffice Desktop Editors is an open-source office suite distributed under AGPL v.3 that combines text, spreadsheet and presentation editors allowing to create, view and edit documents stored on your computer. The application does not require constant connection to the Internet and allows youto create, edit, save and export text, spreadsheet and presentation documents. It is fully compatible with Office Open XML formats: .docx, .xlsx, .pptx. One pack - five editors - multiple features Create, view and edit text documents, spreadsheets and presentations of any size and complexity. Work on documents of most popular formats: DOCX, ODT, XLSX, PDF, ODS, CSV, PPTX, ODP, etc. Deal with multiple files within one and the same window thanks to the tab-based user interface. Highest compatibility with Microsoft Office formats. Real-time collaboration within your favorite cloud Connect ONLYOFFICE Desktop Editors to the cloud platform of your choice: ONLYOFFICE, Nextcloud or ownCloud to collaborate on documents with your team – co-edit in real time, review, comment and interact using chat. Extending your editing capabilities Take the most of your editing with the collection of third-party plugins. Insert a YouTube video, add special symbols or a ClipArt object, automatically translate any word or sentence, highlight code, etc. Do even more! Create your own plugin using the API documentation and ready-to-use examples available on GitHub. OnlyOffice key features: View, edit, and collaborate on docs, sheets, slides Build fillable PDF forms and fill them in online Read and edit PDFs, export/import to/from PDF Convert docs to Markdown and HTML Turn your textbooks into e-books Generate texts with the AI helper OnlyOffice 9.0 changelog: New features All Editors Redesigned interface of the main application window Added new interface themes: Modern Light and Modern Dark Added saving of the last selected languages in spellcheck lists Added Arabic spellcheck dictionary used in sixteen dialects Added AI-powered macro generation from descriptions and VBA-to-JavaScript conversion Added the interface translation into Urdu (ur-PK, Urdu (Pakistan)) Added support for TextArt text settings inside chart labels Added support for drawing the Up/Down Bars chart elements Merged local and cloud template lists into a unified view The list of templates is now processed on the client side, not on the server The installed system languages are now displayed at the top of the text/document/dictionary list Added a contrast-reducing effect for control buttons in inactive windows Added the option to select a printer in the print preview menu The Print using the system dialog option has been added to the print preview menu The ability to configure format associations for modern Windows OS in the EXE package installation wizard has been unlocked Document Editor Added correct display of previews for paragraph numbers for RTL Improved positioning and settings of TextArt for RTL Improved drawing of borders and fill for paragraphs with RTL direction Enabled accurate cursor navigation with arrow keys based on the paragraph's text direction Added the ability to display numbers using Hindi digits Added a setting in the File menu for selecting the preferred font size: Western/Chinese for the Chinese interface language (Chinese (Simplified)) Added a Borders button to the Home toolbar to quickly set paragraph settings Added support for the MD format for reading Spreadsheet Editor Added support for displaying bidirectional text Added the ability to select external data from another spreadsheet Presentation Editor Added the ability to set the paragraph direction (Text Direction > RTL) on the toolbar and in the advanced settings Added the ability to view animations with text Added the "Preserve" option to the Slide Master context menu Forms Changed the appearance of the Signature and Image fields: the placeholder and signature icon are now always displayed Improved user experience when filling in the Signature and Image fields Added a new "type": "signature" for the Signature field, used in the process of filling out forms PDF Editor Added the ability to set RTL direction for text The Edit Text option is available in the Community Edition build Implemented a PDF form editor Added copying pages between PDF files Diagrams Release of the first version of the Diagram Viewer with the ability to open VSDX files for viewing Convert Added conversion of the XLSB format to the editor's internal format, allowing editing and saving in XLSX without preliminary conversion Download: OnlyOffice 64-bit | 273.0 MB (Open Source) Download: OnlyOffice 32-bit | 252.0 MB Download: Windows XP 64-bit | 467.0 MB Download: Windows XP 32-bit | 457.0 MB View: OnlyOffice Website | Screenshot | Release Notes Get alerted to all of our Software updates on Twitter at @NeowinSoftware
    • Awesome! Can't wait to get the stable version on my Surface Pro.
  • Recent Achievements

    • Week One Done
      Wayne Robinson earned a badge
      Week One Done
    • One Month Later
      Karan Khanna earned a badge
      One Month Later
    • Week One Done
      Karan Khanna earned a badge
      Week One Done
    • First Post
      MikeK13 earned a badge
      First Post
    • Week One Done
      OHI Accounting earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      686
    2. 2
      ATLien_0
      273
    3. 3
      Michael Scrip
      205
    4. 4
      +FloatingFatMan
      171
    5. 5
      Steven P.
      145
  • Tell a friend

    Love Neowin? Tell a friend!