Configure CSS for Create-React-App

Jian Ruan
2 min readJan 9, 2017

--

Create-React-App is a great starter to a distraction-free React app. However, anyone who digs a bit deeper will find it annoyingly bad for the philosophy of “no configuration”. It’s simply a pain in the *ss if you just wanna make light modifications on the given.

I searched and searched, but couldn’t anything tailored to my specific needs: modifying the CRA ejected config files to allow postCSS plugins.

I guess it’s quite simple for the Pros, and not a concern for the newbies. And I’m one of the unfortunate in the middle. Since no one puts out a simple and useful guide, I will do it.

In terms of configuration, there are probably thousands of ways for you to make it your own. I will keep the focus on only the CSS part.

There are multiple ways around the limitation. All contain some sort of compromises.

If you looking for tweaking the create-react-app webpack config(s) without using ‘eject’ and without creating a fork of the react-scripts. You can check out: here and here.

But you know what, I choose to eject. Yes, I lose the benefits of CRA integrity and future support. But it just makes the code a lot more organized. Guess I simply don’t enjoying stitching stuff on other stuff.

I did a bunch searching but it turns out to be quite easy.

yarn eject

Then, a folder named config will appear, which contains two webpack related files with names *.dev.js and *.prod.js respectively.

Do the following to both of them.

Substitute

postcss: function() {
return [
autoprefixer({
browsers: [
'>1%',
'last 4 versions',
'Firefox ESR',
'not ie < 9', // React doesn't support IE8 anyway
]
}),
];
}

with

postcss: (webpack) => {
return [
require('postcss-smart-import'),
require('postcss-cssnext'),
require('precss'),
require('lost')
];
}

Don’t forget to get rid of the redundant require statement on the top. This one:

var autoprefixer = require('autoprefixer');

Yeah, you don’t need it.

Some very quick points:

  1. CRA obviously uses webpack v1
  2. postcss-cssnext already contains autoprefixer, that’s why you don’t need it.
  3. Add optional configs after require(‘xx’) structures, same as the default generated by CRA.
  4. Put postcss-smart-import first.
  5. Migrating from Sass/Less to PostCSS makes sense. You can get the sweet part you like in Sass/Less using Precss with only a few exceptions. All you want in .css files without extra dependencies. Given me five.
  6. There are thousands of plugins for PostCSS you can add, what I put there is simply an example.
  7. I recommend adding CSS-Modules. And I recommend doing it through PostCSS.
  8. If you use sublime, package control install Syntax Highlighting for Post​CSS and change default syntax of css to PostCSS in View

If any of the terms in there doesn’t make sense, Google. You will find amazing resources by searching them. Much more than I can put here.

Enjoy React.

--

--