Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Ruby

Thêm Tailwind CSS vào Ruby on Rails: Hướng dẫn thực tế từng bước

CSS thần kỳ nhưng tốn thời gian. Site đẹp, chức năng, accessible là niềm vui, nhưng tự viết CSS rất mệt. Nhiều thư viện CSS như Bootstrap bùng nổ gần đây, và Tailwind dẫn đầu năm 2021.

Mặc dù Rails không có Tailwind out of the box, bài này chỉ cách thêm Tailwind CSS vào dự án Rails mới, tiết kiệm giờ thiết kế. Chúng ta cũng đi qua thiết kế dùng utility classes Tailwind! Phần đầu hướng dẫn tạo Rails project mới và thêm Tailwind từ đầu. Phần sau chỉ cách thêm Tailwind vào project hiện có.

Tailwind CSS là gì?

Tailwind CSS trao quyền developer với utility classes. Các class CSS định nghĩa sẵn này cho building block tạo bất kỳ thiết kế trực tiếp từ HTML. Bạn style bất kỳ element HTML bằng cách append một hoặc nhiều class. Tailwind là thư viện utility khổng lồ với đủ style kết hợp tạo custom design nhanh hơn viết CSS riêng.

Ví dụ, tạo card view với header đẹp chỉ bằng cách apply class cho element muốn style:

<div class="text-center max-w-sm rounded overflow-hidden shadow-lg"> <h1 class="text-3xl font-black">This is a styled header inside a styled card element.</h1> </div> 

Chỉ vậy! Không phải define class và đấu CSS để nó trông như ý. Tailwind đã define đủ utility classes cho hầu hết nhu cầu styling phổ biến.

Nó nhanh chóng được chú ý năm qua như cách developer tiết kiệm thời gian vẫn tạo interface thiết kế tốt nhất quán. Một số dev yêu Tailwind vì lý do này, người khác ghét vì rối HTML.

Setup Tailwind với Rails App mới

Để đơn giản, bao quát build app từ đầu và tạo Rails application mới. Chúng ta dùng phiên bản:

  • Rails 6.1
  • Ruby 3.0.0

rbenv cách chuẩn quản lý Ruby version. Nếu có homebrew, cài brew install rbenv.

Nếu dùng rbenv, cài Ruby 3.0.0 với rbenv install 3.0.0.

Sau đó, chuyển thư mục hiện tại sang Ruby 3.0.0 với rbenv local 3.0.0.

Nếu Ruby version mới, chạy gem install rails.

Tạo Rails Application mới

Bây giờ sẵn sàng Rails 6.1 và Ruby 3.0, tạo app mới bằng rails new tailwind-example. Thay tailwind-example bằng tên khác, nhưng lưu ý phải đổi ở các tham chiếu code/shell khác.

Tiếp, cd vào thư mục project: cd tailwind-example.

Cuối, serve local verify mọi thứ hoạt động: rails server. Mở localhost:3000 trình duyệt xem trang chào Rails! Nếu thấy như sau, đúng đường: Thêm Tailwind CSS vào Ruby on Rails: Hướng dẫn thực tế từng bước

Với Rails app mới chạy, bạn sẵn sàng thêm Tailwind và tạo interface nhanh hơn.

Cài đặt Tailwind CSS

Thêm TailwindCSS dependency bằng yarn add tailwindcss.

Tiếp, dùng lệnh tạo file config tailwind đúng chỗ: npx tailwindcss init.

Mở project và IDE (hurray VS Code!). Mở postcss.config.js ở root project thêm require("tailwindcss"), vào danh sách import. File postcss của tôi:

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

Tiếp, tạo file application.css trong app/javascript. Thêm import sau:

@import "tailwindcss/base"; @import "tailwindcss/utilities"; @import "tailwindcss/components"; 

Tiếp, thêm import "../application.css"; vào imports trong app/javascript/packs/application.js. Điều này đưa tailwind imports vào webpacker. File trông như:

// This file is automatically compiled by Webpack, along with any other files // present in this directory. You're encouraged to place your actual application logic in // a relevant structure within app/javascript and only use these pack files to reference // that code so that it will be compiled. import Rails from "@rails/ujs" import Turbolinks from "turbolinks" import * as ActiveStorage from "@rails/activestorage" import "channels" import "../application.css"; Rails.start() Turbolinks.start() ActiveStorage.start() 

Để dùng Tailwind toàn app, import webpack reference. Trong app/view/layouts/application.html.erb

Tailwind yêu cầu PostCSS 88, Rails 6 chưa update. Nhờ docs, dễ fix bằng cách cài compatibility build Tailwind. Chạy:

npm uninstall tailwindcss postcss autoprefixer npm install -D tailwindcss@npm:@tailwindcss/postcss7-compat @tailwindcss/postcss7-compat postcss@^7 autoprefixer@^9 

Test thử

Để show off CSS library mới, tạo view, controller, model mới. Dễ với Rails scaffolding: rails generate scaffold User email:string password:string.

Tiếp, chạy migration tạo bảng User: rake db:migrate.

Giờ có user model và CRUD cơ bản với view và controller action. Đặt users index page làm root app. Thêm root 'users#index' vào config/routes.rb. Routes file giờ:

Rails.application.routes.draw do root 'users#index' resources :users # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html end 

Chỉ traffic root đến users index. Restart server rails server, vào localhost:3000 thấy: Thêm Tailwind CSS vào Ruby on Rails: Hướng dẫn thực tế từng bước

Chưa thú vị vì:

  1. Chưa có user.
  2. Xấu.

Dễ fix vấn đề 1 bằng cách dùng app. Tailwind giúp vấn đề 2. Click "New User" trên index tạo vài user với pass giả.

Để confirm Tailwind CSS setup đúng, thêm HTML sau vào đầu app/views/users/index.html.erb:

<div class="max-w-lg mx-auto mt-16 text-center max-w-sm rounded overflow-hidden shadow-lg p-10"> <h1 class="mb-4 text-3xl font-black">Here are all our users!</h1> <p class="text-lg leading-snug">If this looks nice, it means Tailwind is set up properly.</p> </div> 

Chỉ div với header và paragraph. Mỗi cái style với Tailwind CSS. Nếu config đúng, trang user trông như: Thêm Tailwind CSS vào Ruby on Rails: Hướng dẫn thực tế từng bước

Giảm kích thước asset với PurgeCSS

Tailwind CSS assets thực sự khổng lồ. Như bạn tưởng tượng, định nghĩa tất cả utility classes cộng lại lớn. Hợp lý chỉ include định nghĩa bạn thực sự dùng. May mắn Tailwind có built-in purge feature làm chính điều đó! Không cần manual pick keep/remove.

Chỉ cần nói cho config Tailwind nơi nhìn, nó tự đi qua và xóa định nghĩa CSS class không dùng. Điều này optimize app cho file size và performance vẫn giữ tùy chọn dùng thêm utility classes bất kỳ lúc nào.

Mở tailwind.config.js ở root project. Giờ trông như:

module.exports = { purge: [], darkMode: false, // or 'media' or 'class' theme: { extend: {}, }, variants: { extend: {}, }, plugins: [], } 

Tiện lợi, chỉ cần đưa file path nơi dùng Tailwind CSS classes. Ví dụ này chỉ dùng trong .html.erb, nên chỉ cung cấp path đó. Nếu app dùng front-end nặng như React hoặc Vue, cung cấp path đó nữa.

Sau khi thêm path, config trông như:

module.exports = { purge: [ "./app/**/*.html.erb", ], darkMode: false, // or 'media' or 'class' theme: { extend: {}, }, variants: { extend: {}, }, plugins: [], } 

Với config này, unused CSS classes bị exclude khi compile với NODE_ENV = production.

Dùng Tailwind CSS Classes tiết kiệm thời gian

Mục đích Tailwind CSS là giúp design tốt hơn, nhất quán, nhanh hơn. Style trang dễ như thêm class name đúng. Lướt docs giúp định hướng, nhưng hãy walk through build user views thấy Tailwind dễ dàng thế nào.

Style User Index Page

Đầu tiên, bọc table stuff trong div để apply style chung. Cho div class class="p-10" (padding 10px). Cũng style h1 tag cho users. 3 class dưới khá tự giải thích, nhưng chú ý mb-4 nghĩa là margin bottom 4px. Sau thay đổi, User Index page đọc như:

<div class="max-w-lg mx-auto mt-16 text-center max-w-sm rounded overflow-hidden shadow-lg p-10"> <h1 class="mb-4 text-3xl font-black">Here are all our users!</h1> <p class="text-lg leading-snug">If this looks nice, it means Tailwind is set up properly.</p> </div> <div class="p-10"> <h1 class="mb-4 text-4xl font-black">Users</h1> <table> <thead> <tr> <th>Email</th> <th>Password</th> <th colspan="3">Actions</th> </tr> </thead> <tbody> <% @users.each do |user| %> <tr> <td><%= user.email %></td> <td><%= user.password %></td> <td><%= link_to 'Show', user %></td> <td><%= link_to 'Edit', edit_user_path(user) %></td> <td><%= link_to 'Destroy', user, method: :delete, data: { confirm: 'Are you sure?' } %></td> </tr> <% end %> </tbody> </table> <br> <%= link_to 'New User', new_user_path %> <div> 

Khá cơ bản, hãy thêm chút spice. Thêm class cho table và button, code kết quả:

<div class="max-w-lg mx-auto mt-16 text-center max-w-sm rounded overflow-hidden shadow-lg p-10"> <h1 class="mb-4 text-3xl font-black">Here are all our users!</h1> <p class="text-lg leading-snug">If this looks nice, it means Tailwind is set up properly.</p> </div> <div class="p-10"> <h1 class="mb-4 text-4xl font-black">Users</h1> <table class="min-w-full table-auto"> <thead class="bg-gray-800 text-gray-300" > <tr> <th>Email</th> <th>Password</th> <th colspan="3">Actions</th> </tr> </thead> <tbody> <% @users.each do |user| %> <tr class="border-4 border-gray-200"> <td><%= user.email %></td> <td><%= user.password %></td> <td><%= link_to 'Show', user %></td> <td><%= link_to 'Edit', edit_user_path(user) %></td> <td><%= link_to 'Destroy', user, method: :delete, data: { confirm: 'Are you sure?' } %></td> </tr> <% end %> </tbody> </table> <br> <%= link_to 'New User', new_user_path, class: "bg-indigo-500 text-white px-4 py-2 border rounded-md hover:bg-white hover:border-indigo-500 hover:text-black" %> <div> 

Thay đổi này cho user index page trông như: Thêm Tailwind CSS vào Ruby on Rails: Hướng dẫn thực tế từng bước

Style New User Page

Khi đang ở đây, restyle trang "New User" hiện có. Hiện tại trông như: Thêm Tailwind CSS vào Ruby on Rails: Hướng dẫn thực tế từng bước

Đầu tiên, apply class mong muốn trong new view cho users. Đây là của tôi:

<div class="bg-grey-lighter min-h-screen flex flex-col"> <div class="container max-w-sm mx-auto flex-1 flex flex-col items-center justify-center px-2"> <div class="bg-white px-6 py-8 rounded shadow-lg text-black w-full"> <h1 class="mb-8 text-3xl text-center">Sign up</h1> <%= render 'form', user: @user %> <div class="text-center text-sm text-grey-dark mt-4"> By signing up, you agree to the <a class="no-underline border-b border-grey-dark text-grey-dark" href="#"> Terms of Service </a> and <a class="no-underline border-b border-grey-dark text-grey-dark" href="#"> Privacy Policy </a> </div> </div> <div class="text-grey-dark mt-6"> Already have an account? <%= link_to 'Sign In', '#', class: "no-underline border-b border-blue text-blue"%> </div> </div> </div> 

Khá tốt trừ form chưa style! Trong app/views/users/_form.html.erb, cần edit. Đây là của tôi:

<%= form_with(model: user) do |form| %> <% if user.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(user.errors.count, "error") %> prohibited this user from being saved:</h2> <ul> <% user.errors.each do |error| %> <li><%= error.full_message %></li> <% end %> </ul> </div> <% end %> <div class="field"> <%= form.label :email %> <%= form.text_field :email, class: "block border border-grey-light w-full p-3 rounded mb-4" %> </div> <div class="field"> <%= form.label :password %> <%= form.text_field :password, class: "block border border-grey-light w-full p-3 rounded mb-4" %> </div> <%= form.submit "Sign Up", class: "w-full text-center py-3 rounded bg-indigo-600 text-white hover:bg-green-dark focus:outline-none" %> <% end %> 

Nhiều edit và class chưa nói, nhưng mọi thứ cần có trong docs. Sau apply class, New User page trông như! Thêm Tailwind CSS vào Ruby on Rails: Hướng dẫn thực tế từng bước

Thêm Tailwind vào App hiện có

Khả năng cao nếu muốn dùng Tailwind, bạn không bắt đầu từ blank slate. Có thể project hiện có với custom CSS nhiều và framework khác như bootstrap. Không sao!

Giả sử app hiện có chạy với Webpacker, làm theo bước "Installing Tailwind CSS" không đổi! Nếu chưa có webpacker, thêm vào Gemfile, chạy bundle install rồi bundle exec rails webpacker:install, sau đó làm theo bước cài Tailwind.

Bạn có thể mix và match custom CSS và Tailwind CSS!

Happy styling!