Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Ruby

เพิ่ม Tailwind CSS ใน Ruby on Rails: คู่มือ Step-by-step ปฏิบัติจริง

CSS เป็น Magic แต่ Time-consuming Beautiful, Functional, และ Accessible Sites เป็น Joy to Use แต่เขียน CSS เอง Exhausting หลาย CSS Libraries เช่น Bootstrap Exploded ใน Recent Years และ Tailwind Leading the Pack ในปี 2021

แม้ Rails ไม่มาพร้อม Tailwind Out of the Box บทความนี้จะแสดงวิธีเพิ่ม Tailwind CSS ใน Ruby on Rails Project ใหม่ ซึ่งจะ Save Hours ใน Design Implementation เราจะ Walk-through Designing ด้วย Utility Classes ของ Tailwind! ส่วนแรกอธิบายสร้าง Rails Project ใหม่และ Add Tailwind ตั้งแต่ต้น ส่วนหลังแสดงเพิ่ม Tailwind ใน Existing Project

Tailwind CSS คืออะไร

Tailwind CSS Empower Developers ด้วย Utility Classes Predefined-defined CSS Classes ให้ Building Blocks สร้าง Design ใดๆ โดยตรงจาก HTML คุณ Style HTML Element ใดๆ ได้โดย Append Classes หนึ่งหรือหลายตัว Tailwind เป็น Massive Utility Library มาพร้อม Styles ทุกอย่าง Combine สร้าง Custom Designs เร็วกว่าเขียน CSS เอง

ตัวอย่าง สร้าง Card View ด้วย Header สวย ด้วย Classes บน Elements ที่อยาก 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> 

แค่นี้! ไม่ต้อง Define Classes และ掙扎 CSS ให้ดูเหมือนที่อยาก Tailwind Defined Utility Classes พอสำหรับ Common Styling Needs

มัน Popular เร็วในปีล่าสุดเป็นวิธี Developers Save Time แต่ยัง Create Consistently Well-designed Interfaces บาง Developers รัก Tailwind เพราะนี้ บางคนเกลียดเพราะ Mess ใน HTML

Setup Tailwind กับ New Rails App

For Simplicity เราจะ Cover Build App From Scratch และ Create New Rails Application เราจะใช้ Versions นี้:

  • Rails 6.1
  • Ruby 3.0.0

rbenv Standardized Way Manage Ruby Versions ถ้ามี Homebrew Install brew install rbenv

ถ้าใช้ rbenv Install Ruby 3.0.0 ด้วย rbenv install 3.0.0

Switch Current Directory Ruby 3.0.0 ด้วย rbenv local 3.0.0

ถ้า Ruby Version ใหม่ gem install rails

Creating a New Rails Application

ตอน Ready Rails 6.1 และ Ruby 3.0 สร้าง New Rails App ด้วย rails new tailwind-example แทน tailwind-example ด้วยชื่ออื่นได้ แต่ Note ว่าต้อง Swap ใน Code/Shell References อื่นๆ

Change Directory: cd tailwind-example

Serve Locally Verify Working: rails server ไป localhost:3000 ใน Browser ดู Rails Welcome Page ถ้าเห็นแบบนี้ On Right Path: เพิ่ม Tailwind CSS ใน Ruby on Rails: คู่มือ Step-by-step ปฏิบัติจริง

With Fresh Rails App Up and Running Ready to Add Tailwind และ Start Creating Interfaces Faster

Installing Tailwind CSS

แรก Add TailwindCSS Dependency ด้วย yarn add tailwindcss

ต่อไป Command สร้าง Tailwind Config File ในที่ถูกต้อง: npx tailwindcss init

เปิด Project และ IDE (Hurray for VS Code!) เปิด postcss.config.js ใน Project Root เพิ่ม require("tailwindcss"), ใน Imports List นี่ postcss file ของผม:

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

ต่อไป สร้าง File application.css ใน app/javascript ใส่ Imports:

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

เพิ่ม import "../application.css"; ใน Imports ใน app/javascript/packs/application.js นำ Tailwind Imports เข้า Webpacker File ควรเป็น:

// 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() 

To Use Tailwind Across Application ต้อง Import Webpack Reference ใน app/view/layouts/application.html.erb

Tailwind ต้องการ PostCSS 88 และ Rails 6 ยังไม่ Update Thanks to Docs เรา Fix ได้ง่ายด้วย Tailwind's Compatibility Build รัน:

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

Testing It Out

Show Off New CSS Library เราจะ Create New View, Controller, Model ด้วย Rails Scaffolding: rails generate scaffold User email:string password:string

Run DB Migration Create User Table: rake db:migrate

ตอนนี้มี User Model และ Basic CRUD Capabilities พร้อม Views และ Controller Actions Set Users Index Page เป็น Root ของ App เพิ่ม root 'users#index' ใน config/routes.rb Routes File ควรเป็น:

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 

Direct Traffic at Root ไป Users Index Page Restart Rails Server rails server ไป localhost:3000 ควรเห็น: เพิ่ม Tailwind CSS ใน Ruby on Rails: คู่มือ Step-by-step ปฏิบัติจริง

Not Interesting สองเหตุผล: 1. No Users 2. Ugly

Fix First Problem ด้วย Using App เอง Tailwind ช่วย Second ไป Create Users ด้วย Fake Passwords

Confirm Tailwind CSS Setup Properly ใส่ HTML นี้ Top ของ 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> 

แค่ Div พร้อม Header และ Paragraph แต่ละอัน Styled ด้วย Tailwind CSS ถ้า Configured Properly User Page ควรเป็น: เพิ่ม Tailwind CSS ใน Ruby on Rails: คู่มือ Step-by-step ปฏิบัติจริง

ลด Asset Size ด้วย PurgeCSS

Tailwind CSS Assets จริงๆ Massive มาก ตามที่นึกได้ Definition ของ Utility Classes ทั้งหมด Adds Up Makes Sense ให้ Include แค่ Definitions ที่ Actually Using โชคดี Tailwind CSS มาพร้อม Built-in Purge Feature ทำได้! ไม่ต้อง Manual Pick and Choose

แค่บอก Tailwind Config Where to Look มัน Auto Go Through Remove Definitions ของ Unused CSS Classes 让我们 Optimize App สำหรับ File Size และ Performance ยัง Retain Option ใช้ Utility Classes มากขึ้นได้

เปิด tailwind.config.js ใน Project Root ควรเป็น:

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

Conveniently แค่ให้ File Path ที่อาจใช้ Tailwind CSS Classes ตัวอย่างนี้แค่ .html.erb Files นั่นคือ All We Provide แต่ถ้า App ใช้ Heavy Front-end เช่น React หรือ Vue จะ Provide Paths นั้นๆ ด้วย

หลัง Add Paths Config File ควรเป็น:

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

With This Config Unused CSS Classes Excluded When Compile ด้วย NODE_ENV = production

ใช้ Tailwind CSS Classes Save Time

Whole Point ของ Tailwind CSS คือ Help Design Better, More Consistently, และ Faster Styling Page = Add Right Class Names Glance Through Docs Super Helpful Get Oriented แต่ Walk Through Building User Views ให้ Idea ว่า Tailwind ทำ Styling Easy แค่ไหน

Styling the User Index Page

First Thing Index Page เรา Put Table Stuff ใน Div ให้ Apply Styles as a Whole ให้ Div Class class="p-10" = 10px Padding Apply Styling h1 Tag สำหรับ Users 3 Classes ด้านล่าง Self-explanatory แต่ Note mb-4 = 4px Margin Bottom หลัง Changes User Index Page ควรเป็น:

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

Pretty Basic Spice Up ใส่ Classes สำหรับ Table และ Button ผล Code ของผม:

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

Adding Changes User Index Page เป็น: เพิ่ม Tailwind CSS ใน Ruby on Rails: คู่มือ Step-by-step ปฏิบัติจริง

Styling the New User Page

While At It Restyle Existing "New User" Page ปัจจุบันเป็น: เพิ่ม Tailwind CSS ใน Ruby on Rails: คู่มือ Step-by-step ปฏิบัติจริง

First Apply Desired Classes ใน New View สำหรับ Users นี่ของผม:

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

Pretty Good Except Form Itself Not Styled Yet! ใน app/views/users/_form.html.erb ยัง Edit นี่ของผม:

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

Lot of Edits และ Classes ใหม่ Everything You'd Need ใน Docs หลัง Apply Classes New User Page ตอนนี้: เพิ่ม Tailwind CSS ใน Ruby on Rails: คู่มือ Step-by-step ปฏิบัติจริง

Adding Tailwind to an Existing App

Odds Are Good ถ้าอยากใช้ Tailwind คุณไม่ Start From Blank Slate คุณมี Existing Project Custom CSS และ Frameworks อื่นๆ เช่น Bootstrap Totally Fine!

Assuming Existing App Running With Webpacker Follow Steps ใน "Installing Tailwind CSS" Without Changes! ถ้าไม่มี Webpacker Add to Gemfile Run bundle install และ bundle exec rails webpacker:install แล้ว Follow Tailwind Installation Steps

You Can Then Mix and Match กับ Existing CSS และ Tailwind CSS!

Happy Styling!