DEV Community

loading...
Cover image for Webpacker 6: Tailwind CSS 2.0 Integration

Webpacker 6: Tailwind CSS 2.0 Integration

andrewmcodes profile image Andrew Mason Originally published at andrewm.codes Updated on ・2 min read

In order to add Tailwind CSS 2.0 to your Rails 6 + Webpacker 6 application, you need PostCSS set up, plus a few additional steps.

Tailwind CSS has detailed documentation on preprocessor usage so refer to that for further setup.

Note: This section builds on the PostCSS section

Install

yarn add tailwindcss
Enter fullscreen mode Exit fullscreen mode

Add Tailwind CSS Config File

yarn tailwind init
Enter fullscreen mode Exit fullscreen mode

Update PostCSS Config

// postcss.config.js

module.exports = {
  plugins: [
    require('postcss-import'),
+   require('tailwindcss'),
    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:

touch app/javascript/stylesheets/base.css
echo "@import 'tailwindcss/base';" >> app/javascript/stylesheets/base.css
touch app/javascript/stylesheets/utilities.css
echo "@import 'tailwindcss/utilities';" >> app/javascript/stylesheets/utilities.css
touch app/javascript/stylesheets/components.css
echo "@import 'tailwindcss/components';" >> app/javascript/stylesheets/components.css
Enter fullscreen mode Exit fullscreen mode

Next, add some CSS:

/* app/javascript/stylesheets/base.css */

@import "tailwindcss/base";

+ 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.css";
@import "../stylesheets/components.css";
@import "../stylesheets/utilities.css";
Enter fullscreen mode Exit fullscreen mode

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

Discussion (0)

pic
Editor guide