DEV Community

Cover image for Webpacker 6: PostCSS Loaders
Andrew Mason
Andrew Mason

Posted on • Updated on • Originally published at andrewm.codes

Webpacker 6: PostCSS Loaders

In order to process .pcss files with Webpacker 6, you need to add postcss-loader. I am also going to add PostCSS 8 support.

Note: This section builds on the CSS section

Install

yarn add postcss-loader postcss@latest autoprefixer@latest postcss-import@latest
Enter fullscreen mode Exit fullscreen mode

Add PostCSS Config File

touch postcss.config.js
Enter fullscreen mode Exit fullscreen mode
// postcss.config.js

module.exports = {
  plugins: [
    require('postcss-import'),
    require('autoprefixer')
  ]
}
Enter fullscreen mode Exit fullscreen mode

Usage

You should be able to use the same pack tag that you added for CSS.

Make sure you restart bin/webpack-dev-server after installing new loaders.

Style Loader Example

<%# app/views/layouts/application.html.erb %>

+ <%= stylesheet_packs_with_chunks_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_packs_with_chunks_tag 'application', 'data-turbolinks-track': 'reload' %>
Enter fullscreen mode Exit fullscreen mode

Extract Example

<%# app/views/layouts/application.html.erb %>

<%= javascript_packs_with_chunks_tag 'application', 'data-turbolinks-track': 'reload' %>
+ <%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
Enter fullscreen mode Exit fullscreen mode
// app/javascript/packs/application.js

+ import "./application.css"
Enter fullscreen mode Exit fullscreen mode

Verify

Note: Make sure you restart the dev server!

Let’s create a new PostCSS file:

mkdir app/javascript/stylesheets
touch app/javascript/stylesheets/base.pcss
Enter fullscreen mode Exit fullscreen mode

Next, add some CSS:

/* app/javascript/stylesheets/base.pcss */

h1 {
  font-size: 2.2em;
  color: #2563eb;
}

p {
  font-size: 1.2em;
}
Enter fullscreen mode Exit fullscreen mode

Lastly, update application.css:

/* app/javascript/packs/application.css */

@import "../stylesheets/base.pcss";
Enter fullscreen mode Exit fullscreen mode

Reload your browser and your styles should be applied now, and the Webpacker loader error should be gone.

Discussion (1)

Collapse
juanvqz profile image
Juan Vasquez

I had all this config in postcss.config.js

module.exports = {
  plugins: [
    require("postcss-import"),
    require("autoprefixer"),
    require("postcss-flexbugs-fixes"),
    require("postcss-preset-env")({
      autoprefixer: {
        flexbox: "no-2009",
      },
      stage: 3,
    }),
  ],
}
Enter fullscreen mode Exit fullscreen mode

and it fails then I just leave the lines as the post explain

module.exports = {
  plugins: [require("postcss-import"), require("autoprefixer")],
}
Enter fullscreen mode Exit fullscreen mode

and it works flying colors 🚀