🚀 Kosol.net

Published

- 2 min read

Create SvelteKit and Tailwind project.

img of Create SvelteKit and Tailwind project.

สำหรับคนที่กำลังมองหา CSS Framework สำหรับมาใช้ร่วมกับ SvelteKit Project แต่ยังไม่รู้จะเลือกตัวไหนดี ขอแนะนำ Tailwind CSS ที่จะช่วยให้คุณตกแต่งเว็บได้ง่ายๆ

โดยบทความนี้จะแนะนำขั้นตอนการติดตั้ง Tailwind CSS โดยมีขั้นตอนดังนี้

Setup SvelteKit and Tailwind project.

  1. New SvelteKit Project with this command.

ขั้นตอนแรกสร้าง SvelteKit Project กันก่อน

   npm create svelte@latest svelte-tailwind-app
cd svelte-tailwind-app
npm install
npm run dev -- --open
  1. Install Tailwind with this command.

จากนั้นติดตั้ง TailwindCSS, postcss, AutoPrefixer เสร็จแล้วรันคำสั่ง npx tailwindcss init -p สร้างไฟล์ tailwindConfig.config.js

   npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p
  1. Create and open tailwind.config.js file in project root folder and add this code.

เปิดไฟล์ tailwind.config.js จากนั้นไปที่บรรทัด Content เพิ่ม path และ นามสกุลไฟล์ที่เกี่ยวข้องกับ htmlWhitespaceSensitivity, svelte, js, ts

   content: ['./src/**/*.{html,js,svelte,ts}'],

หลังจากเพิ่มแล้วหน้าตาไฟล์ tailwind.config.js จะได้ประมาณนี้

   /** @type {import('tailwindcss').Config} */
export default {
	content: ['./src/**/*.{html,js,svelte,ts}'],
	theme: {
		extend: {}
	},
	plugins: []
}
  1. Create app.css file in ./src folder and add the tailwind directives to this file.

ขั้นต่อไปสร้างไฟล์​ app.css ในโฟลเดอร์ ./src แล้วใส่ 3 บรรทัดนี้เพื่อให้ Tailwind สร้าง css ให้เราตอนรันโปรแกรม

   @tailwind base;
@tailwind components;
@tailwind utilities;
  1. Create +layout.svelte file in ./src/routes folder and add this code.

จากนั้นให้สร้างไฟล์ชื่อ +layout.svelte ไว้ที่โฟลเดอร์ ./src/routes แล้วเรียกใช้ app.css ที่สร้างไว้ในขั้นตอนก่อนหน้า

   <script>
  import "../app.css";
</script>

<slot />
  1. Edit file +page.svelte in ./src folder and add this code for prepare test

จากนั้นลองใส่ class ใน h1 tag เพื่อใช้ class ของ Tailwind CSS

   <h1 class="text-3xl font-bold text-blue-400 py-8 text-center">Hello world!</h1>

<style lang="postcss">
	:global(html) {
		background-color: theme(colors.gray.900);
	}
</style>
  1. Run program with this command and view result in browser.

ขั้นสุดท้ายทดสอบรันโปรแกรมโดยใช้คำสั่ง npm run dev แล้วดูผลลัพธ์

   npm run dev -- --open

The result will show blue text Hello World in the top left of screen.

   Hello World

บทความที่เกี่ยวข้อง