Site is under renovation and you may experience weirdness.

Webpacker 6: PostCSS Loaders

Andrew Mason

Andrew Mason

Updated Jan 9th, 2022


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

Add PostCSS Config File

touch postcss.config.js
// postcss.config.js

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

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' %>

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' %>
// app/javascript/packs/application.js

+ import "./application.css"

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

Next, add some CSS:

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

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

p {
  font-size: 1.2em;
}

Lastly, update application.css:

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

@import "../stylesheets/base.pcss";

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


Series
webpacker-6

Discuss
on Twitter↗
Updated On
Jan 9th, 2022
Published On
Dec 23rd, 2020
Word Count
294 words
Reading Time
2 min read