RailsにTailwindCSSを導入する
2020/12/23
Rails6.1にTailwind CSS v1.9.6を導入した手順。
Tailwind CSSのv2系はまだ対応していない部分が多いため、v1.9.6にした。
参考: https://tailwindcss.com/docs/installation#post-css-7-compatibility-build
環境
- Ruby: 2.7.2
- Rails: 6.1.0
- Node.js: v12.20.0
- Yarn: 1.22.5
手順
Tailwind CSSの導入
$ yarn add [email protected]
$ yarn tailwindcss init # tailwind.config.jsというファイルが生成される
$ mkdir app/javascript/css
$ vim app/javascript/css/tailwindcss.css
$ vim app/javascript/packs/application.js
$ vim app/views/layouts/application.html.erb
$ vim postcss.config.js
tailwind.config.js
module.exports = {
purge: [],
darkMode: false, // or 'media' or 'class'
theme: {
extend: {},
},
variants: {
extend: {},
},
plugins: [],
}
app/javascript/css/tailwindcss.css
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";
app/javascript/packs/application.js
import Rails from "@rails/ujs"
import Turbolinks from "turbolinks"
import * as ActiveStorage from "@rails/activestorage"
import "channels"
+ import "../css/tailwindcss.css";
Rails.start()
Turbolinks.start()
ActiveStorage.start()
app/views/layouts/application.html.erb
<head>
<title>App</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
- <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
+ <%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
</head>
postcss.config.js
module.exports = {
plugins: [
+ require('tailwindcss'),
+ require('autoprefixer'),
require('postcss-import'),
require('postcss-flexbugs-fixes'),
require('postcss-preset-env')({
autoprefixer: {
flexbox: 'no-2009'
},
stage: 3
})
]
}
動作確認
適当のページを作って確認する。
$ rails g controller home index
vim app/views/home/index.html.erb
app/views/home/index.html.erb
<div class="max-w-md mx-auto bg-white rounded-xl shadow-md overflow-hidden md:max-w-2xl">
<div class="md:flex">
<div class="md:flex-shrink-0">
<img class="h-48 w-full object-cover md:w-48" src="https://placehold.jp/500x500.png" alt="Man looking at item at a store">
</div>
<div class="p-8">
<div class="uppercase tracking-wide text-sm text-indigo-500 font-semibold">Case study</div>
<a href="#" class="block mt-1 text-lg leading-tight font-medium text-black hover:underline">Finding customers for your new business</a>
<p class="mt-2 text-gray-500">Getting a new business off the ground is a lot of hard work. Here are five ideas you can use to find your first customers.</p>
</div>
</div>
</div>