TailwindCSSをSvelteKitで使う方法
2021年12月4日に投稿、2022年8月20日に更新
SvelteKitでTailwindCSSをセットアップするのは、数週間前に比べて今はずっと簡単になりました。でも、どうやってセットアップするのか探すのに手間がかかるかもしれないので、基本的なセットアップ方法を教えます。
2022年8月20日更新 - 早いバージョンのSvelteKitを使っている人のためにオリジナルの内容を投稿の最後に残しています
SvelteKitのドキュメント
TailwindCSSのドキュメント
また興味があるかもしれない
SvelteKit + .env
SvelteKit + Heroku
更新された内容
Svelteアプリを作成する
npm create svelte@latest my-app
cd my-app
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init tailwind.config.cjs -p
注:公式のTailwindドキュメントではsvelte-preprocessのインストールが必要とされていますが、この文章を書いている時点でそれはスケルトンに含まれています
設定ファイルを更新する
svelte.config.js
import preprocess from "svelte-preprocess";
const config = {
preprocess: [
preprocess({
postcss: true,
}),
],
};
tailwind.config.cjs
/** @type {import('tailwindcss').Config} */
module.exports = {
content: ['./src/**/*.{html,js,svelte,ts}'],
theme: {
extend: {},
},
plugins: [],
};
src
ルートにapp.css
を作成する
ボイラープレートのCSSを削除する(demoテンプレートを使用している場合)または、スケルトンを使用している場合はapp.css
@tailwind base;
@tailwind components;
@tailwind utilities;
./src/routes/+layout.svelte
を作成する、またはdemoテンプレートを使用している場合はそれを確認する
スケルトンを使用している場合は+layout.svelte
<script>
import "../app.css";
</script>
<slot />
オリジナルの内容
Svelteアプリを作成する
npm create svelte@latest my-app
cd my-app
npx svelte-add@latest tailwindcss
npm i
app.css
を作成する
ボイラープレートのCSSを削除する(demoテンプレートを使用している場合)または、スケルトンを使用している場合はapp.css
@tailwind base;
@tailwind components;
@tailwind utilities;
Tailwindの色を使う
3.xリリースで全ての色が含まれています。独自の色を追加したり、Tailwindが提供する色の名前を変えたりしたい場合には、設定ファイルで行うことができます:
tailwind.config.cjs
// 先頭に追加
const colors = require('tailwindcss/colors');
// 設定内に追加
colors: {
// ここに色を追加
},
これでセットアップは完了です。
こちらの記事はdev.toの良い記事を日本人向けに翻訳しています。
https://dev.to/nostro/using-tailwindcss-with-sveltekit-25i6