1. 建立專案

    如果你尚未設定新的 SvelteKit 專案,請先從建立新的 SvelteKit 專案開始。最常見的方法概述於 開始使用 SvelteKit 簡介中。

    終端機
    npm create svelte@latest my-projectcd my-project
  2. 安裝 Tailwind CSS

    安裝 tailwindcss 及其對等相依項,然後產生你的 tailwind.config.jspostcss.config.js 檔案。

    終端機
    npm install -D tailwindcss postcss autoprefixernpx tailwindcss init -p
  3. 在 <style> 區塊中啟用 PostCSS

    在您的 svelte.config.js 檔案中,匯入 vitePreprocess 以啟用將 <style> 區塊處理為 PostCSS。

    svelte.config.js
    import adapter from '@sveltejs/adapter-auto';
    import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';
    /** @type {import('@sveltejs/kit').Config} */
    const config = {
      kit: {
        adapter: adapter()
      },
      preprocess: vitePreprocess()
    };
    export default config;
    
  4. 設定您的範本路徑

    在您的 tailwind.config.js 檔案中,新增所有範本檔案的路徑。

    tailwind.config.js
    /** @type {import('tailwindcss').Config} */
    export default {
      content: ['./src/**/*.{html,js,svelte,ts}'],
      theme: {
        extend: {}
      },
      plugins: []
    };
    
  5. 在您的 CSS 中新增 Tailwind 指令

    建立一個 ./src/app.css 檔案,並為 Tailwind 的每個圖層新增 @tailwind 指令。

    app.css
    @tailwind base;
    @tailwind components;
    @tailwind utilities;
  6. 匯入 CSS 檔案

    建立一個 ./src/routes/+layout.svelte 檔案,並匯入新建立的 app.css 檔案。

    +layout.svelte
    <script>
      import "../app.css";
    </script>
    
    <slot />
  7. 開始您的建置程序

    使用 npm run dev 執行您的建置程序。

    終端機
    npm run dev
  8. 開始在您的專案中使用 Tailwind

    開始使用 Tailwind 的實用程式類別來設定您的內容樣式,請務必為任何需要由 Tailwind 處理的 <style> 區塊設定 lang="postcss"

    +page.svelte
    <h1 class="text-3xl font-bold underline">
      Hello world!
    </h1>
    
    <style lang="postcss">
      :global(html) {
        background-color: theme(colors.gray.100);
      }
    </style>