Today I Learned

2 posts by dariuszpieńczykowski

How to add autoprefixer in webpack

Firstly we need to add this to our project using yarn/npm.

So yarn add autoprefixer.

After a successful installation, we need to declare which browsers we wanna use for our autoprefixer.

To declare that, we need to add to our packages.json file a few lines:

“browserslist”: [
   “> 1%“,
   “last 2 versions”
 ],

here, we can set something else (https://github.com/browserslist/browserslist#queries)

After that, we need to configure the webpack config file (ie. webpack.config.js).

Firstly we require autoprefixer and we’re setting this as a variable (somewhere on the beginning of the file)

const autoprefixer = require('autoprefixer');

!important:

| We need to add postcss-loader loader between css-loader and sass-loader.

use: ['css-loader',
            {
              loader: 'postcss-loader',
              options: {
                plugins: () => [autoprefixer()]
              }
            },
            'sass-loader'],

if we have more loaders it could look like that:

  module: {
    rules: [
      {
        test: /\.(sass|scss)$/,
        loader: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: ['css-loader',
            {
              loader: 'postcss-loader',
              options: {
                plugins: () => [autoprefixer()]
              }
            },
            'sass-loader'],
        }),
      },
      {
        test: /\.css$/,
        loader: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: ['css-loader'],
        }),
      },
      {
        test: /\.js/,
        use: ['babel-loader?cacheDirectory'],
        exclude: /node_modules/,
      },
    ],
  },

Now, we need to restart the server and you can enjoy working autoprefixer :)

SASS / BEM - Not TIL but still some interesting magic

Case 1 - we don’t want to write parent classname again from deep nesting

.some-class
  $this: &

  &.--sub
    margin-top: 2.4rem
    #{$this}__title // so it is .some-class__title
      font-size: 1.7rem

equals:

.some-class.--sub
  margin-top: 2.4rem
.some-class.--sub .some-class__title
  font-size: 1.7rem

Case 2 - we want to have a (or any another tag) before parent class from deep nesting

.btn
  margin-top: 2.4rem
  @at-root a#{&} // so it is a.btn
    font-size: 1.7rem

equals:

.btn
  margin-top: 2.4rem
a.btn
  font-size: 1.7rem