loading...

Creating Tiny Bootstrap Builds With Webpack

kayis profile image K ・2 min read

TL;DR Here is a repository with a working example. :)

Almost everyone developing for the Web has read of Bootstrap, the CSS framework from Twitter. It's easy to theme and well know in the whole industry, so if you have no strong opinion about CSS, it's probably a good start.

Why?

Problem is, it's freaking huge. A normal Bootstrap build, delivered from a content delivery network (CDN) is ~120KB big. Often clients have already cached this, because many pages use the same CDN links, but sometimes you don't want or can rely on external resources.

The smaller the better, because the fastest bit is the bit not sent and a penny saved is a dollar earned!

The the idea here is, to make a custom build of Bootstrap, but not with the Web-interface, but with the Less source of Bootstrap and Webpack.

How?

First you get Bootstrap via npm.

Next, you need some loaders and a plugin for Webpack. The style-loader, css-loader, sass-loader and the extract-text-plugin.

The rule for your less files in the webpack.config.js looks like this:

  {
    test: /\.less$/,
    use: ExtractTextPlugin.extract({
      fallbackLoader: 'style-loader',
      loader: [
        {loader: 'css-loader', options: {minimize: true}},
        'less-loader',
      ],
    })
  }
  ...
  plugins: [new ExtractTextPlugin('style.css')]

This will tell Webpack how to load your Less files, compile them to CSS and then extract this CSS from the JS bundles into a CSS file.

Also, since Webpack now understands Less, you can use a less file directly as entry.

entry: {style: './src/index.less'}

The Bootstrap sources consist of a few Less files, all imported by the bootstrap.less, which normally serves as the entry point to compile the whole thing.

But we do not want the whole thing because it's huge!

So what we do is copying the content of the bootstrap.less file into our own less file and then comment out what we don't need.

Take this example:

@import "node_modules/bootstrap/less/variables.less";
@import "node_modules/bootstrap/less/mixins.less";
@import "node_modules/bootstrap/less/normalize.less";
@import "node_modules/bootstrap/less/scaffolding.less";
@import "node_modules/bootstrap/less/type.less";
@import "node_modules/bootstrap/less/grid.less";
@import "node_modules/bootstrap/less/forms.less";
@import "node_modules/bootstrap/less/buttons.less";

If you don't use glyphicons, tables, print-views, code, or components, you can get this whole bundle down to 33KB (pre gzip). Maybe you just need the basic CSS and would like to do your own components, or you want to do a simple formular without much extras.

You can also use a post-css loader to add vendor prefixes.

Posted on by:

kayis profile

K

@kayis

Taking care of developer relations at Moesif and creating educational content at fllstck.dev

Discussion

markdown guide