Set Up Styles in Webpack

  • Style loaders
  • CSS Modules

Now that we have a few routes set up, we should start building out our frontend components so we can render something more interesting to the user. But before we do that, we need to configure our styling.

There is a seemingly limitless number of options when it comes to styling. You have LESS, Sass, Stylus, plain-old CSS, as well as extra features such as PostCSS and CSSNext, autoprefixers, and some React-specific bits such as the style-loader, and react-css-modules.

We are going to use the following, and we'll go over why:

  • style-loader and css-loader
  • react-css-modules
  • postcss-loader
  • postcss-cssnext

Preprocessors (LESS, Sass, Coffeescript, etc) save countless hours of development time and allow for additional features. That said, the next CSS specs are pretty similar to what you'll get from a preprocessor and postcss-cssnext gives you all of those features now. You can think of it as Babel for styles. Also, CSSNext gives you a built-in autoprefixer, so we won't need to install one ourselves.

The style-loader and css-loader are loaders that every React project needs in order to add styling to a component. After you compile down to CSS, you need to use the style-loader to put that CSS into your React component, so you will always see it as the last loader in any styling configuration. For example:

{ test: /\.scss$/, loaders: 'style!css!sass' }

So, in effect, you are starting with a .scss file, converting it to CSS, then using the style-loader to add that CSS to your React component.

We are also using an autoprefixer so we don't have to worry about those pesky vendor prefixes. Remember, this is built-in to the latest version of postcss-cssnext. If you are not familiar with vendor prefixes, they are those annoying extra bits of styling you need to add to make your styles work with different browsers.

-webkit- (Chrome, newer versions of Opera.)
-moz- (Firefox)
-o- (Old versions of Opera)
-ms- (Internet Explorer)

These prefixes exist because when a new experimental CSS feature is proposed, browsers will try to implement that feature differently. The prefix tells the browser how to apply that style in a way that is compatible with the browser you are using.

The last piece we're going to add is also the most interesting. The react-css-modules configuration allows you create locally-scoped CSS, so you no longer need to keep a massive dictionary of globally-scoped CSS! Or as it says in the docs:

A CSS Module is a CSS file in which all class names and animation names are scoped locally by default. All URLs (url(...)) and @imports are in module request format (./xxx and ../xxx means relative, xxx and xxx/yyy means in modules folder, i. e. in node_modules).

React CSS Modules is likely to become the new gold-standard of organizing styles, as it is much easier to create and manage styles in JavaScript than it is in CSS.

Webpack configuration

The first thing to do is to add the necessary dependencies to our package.json file:

$ npm install --save-dev style-loader css-loader \
postcss-loader postcss-cssnext
$ npm install --save react-css-modules

But first, we have to set up the loader to handle CSS files. We're also going to have to do some additional configuration to get our CSS modules working properly.

module: {
loaders: [
...
{
test: /\.css$/,
loader: 'style!css?modules&importLoaders=1&localIdentName=[local]_[hash:base64:5]!postcss',
include: path.join(__dirname, 'app'),
exclude: /node_modules/
}
]
}

This probably looks confusing because of the way the modules loader works. In the code above, we are effectively calling in order (recall, it runs from right to left) postcss, css with the modules option, and then style. The confusing bit is that modules has a bunch of options that you pass into it.

The first option is importLoaders, which you set to 1, which simply means "true".

The second option is localIdentName, which you set to an expression that looks like this: [local]_[hash:base64:5]. This will take the name of the local style (for example .column), and add a randomly generated string of 5 characters at the end of it. So, in the example above, you might end up with a class of column_3nrwE.

Now we need to configure our postcss loader to use the autoprefixer. Fortunately, this is quite simple. Within our webpack.config.js file, add the following (make sure you add cssnext at the top of the file):

var cssnext = require('postcss-cssnext')
...
module: {
...
},
resolve: {
...
},
postcss: function () {
return [cssnext]
},
...

Resetting default css and globals

We're almost ready to get started making some components. The last thing we need to do is remove the default styling provided by our browser. You can do this with a global reset stylesheet (which is what we're using), or you can use a package like Normalize. It's a matter of preference and it depends on the level of customization you want.

Within our app directory, create a new directory called styles and create a new file called reset.css:

$ mkdir app/styles
$ touch app/styles/reset.css

Within this directory, we will create all of our shared styles. This will include things like buttons, forms and inputs, and any other styles that are shared across multiple components.

We are not going to use a frontend framework such as Bootstrap or Foundation. We are going to build all of our own styles from scratch. If this sounds intimidating, I assure you it is not as much work as you think. We are going to copy the global reset from meyerweb.com, with a few slight variations. Copy and paste the following into your reset.css file:

/* http://meyerweb.com/eric/tools/css/reset/
v2.0 | 20110126
License: none (public domain)
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
color: #333;
padding: 0;
border: 0;
font-size: 100%;
font-family: "Roboto", arial, sans-serif;
vertical-align: baseline;
box-sizing: border-box;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
a {
color: #42A5F5;
text-decoration: none;
}

And to have this reset take effect, import them to the top of your app/index.js file:

import "./styles/reset.css"
...

Remember, when you make changes to your webpack configuration, you need to restart your node server for those changes to take effect.

At this point, you probably understand the sentiment behind JavaScript Fatigue... but at least we're almost ready to start building our app!

Previous: Routes and ViewsNext: Style a React Component