PostCSS is a tool for transforming CSS with JavaScript. To enable it in a Rails application, I needed to make the following changes to my app. Please note that my app does not use turbolinks.
/app/views/layouts/application.html.erb
Update so that the style sheet directive in the header uses stylesheet_pack_tag. That is, replace:
<%= stylesheet_link_tag 'application', media: 'all' %>
With:
<%= stylesheet_pack_tag 'application', media: 'all' %>
Sorry – opening brackets aren’t rendering nicely using the code include I’m using in this blog. Both declarations should start with a less than chevron.
/package.json
Add postcss dependencies to package.json:
{
"name": "my_app",
"private": true,
"dependencies": {
"@rails/actioncable": "^6.0.0-alpha",
"@rails/activestorage": "^6.0.0-alpha",
"@rails/ujs": "^6.0.0-alpha",
"@rails/webpacker": "^4.0.7",
"polyfill-nodelist-foreach": "^1.0.1",
"postcss-browser-reporter": "^0.6.0",
"postcss-import": "^12.0.1",
"postcss-inline-svg": "^4.1.0",
"postcss-preset-env": "^6.7.0",
"postcss-reporter": "^6.0.1",
"postcss-svgo": "^4.0.2"
},
"version": "0.1.0",
"devDependencies": {
"webpack-dev-server": "^3.9.0"
}
}
/postcss.config.js
Add the following content to a file called
module.exports = () => ({
plugins: [
require("postcss-import"),
require("postcss-preset-env")({
autoprefixer: {},
features: {
"focus-within": true,
"nesting-rules": true,
"color-mod-function": {
unresolved: "warn"
},
"custom-properties": {
preserve: false,
warnings: true
}
}
}),
require("postcss-browser-reporter"),
require("postcss-reporter")
]
});
I believe that the rails webpacker stack already contains the PostCSS packages, but you may have to install them via yarn. I didn’t but then I have been trying to get this to work for a couple of days and may have installed them via another mechanism.
With the the above changes in place, I was then able to load PostCSS files. Note that it was simplest to do this via the javascript folder as they needed to be accessed relative to packs application.js file.
So as an example, I created the following file:
/app/javascript/packs/test.css
html,
body {
background: lightyellow;
}
Then to enable it I had to modify /app/javascript/packs/application.js by adding the following line:
import './test.css'
When I ran my app, the background turned yellow as expected.
One thing to note is that once these changes have been put in place, the sass stylesheets in /app/stylesheets are no longer loaded by the app.