在 Vue 3 和 Vite 安裝 Tailwind CSS

2022-07-23 11:41 更新

創(chuàng)建您的工程

如果您還沒有建立一個新的 Vite 項目,請先創(chuàng)建一個新的項目。

npm init vite my-project
cd my-project

接下來,使用 ?npm ?安裝 Vite 的前端依賴關(guān)系。

npm install

初始化 Tailwind CSS

Tailwind CSS 需要 Node.js 12.13.0 或更高版本。

通過 npm 安裝 Tailwind

npm install -D tailwindcss@latest postcss@latest autoprefixer@latest

創(chuàng)建您的配置文件

接下來,生成您的 ?tailwind.config.js? 和 ?postcss.config.js? 文件:

npx tailwindcss init -p

這將會在您的項目根目錄創(chuàng)建一個最小化的 ?tailwind.config.js? 文件:

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

這也將會創(chuàng)建一個包含已配置好的 ?tailwindcss ?和 ?autoprefixer ?的 ?postcss.config.js? 配置文件:

// postcss.config.js
module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
}

配置 Tailwind 來移除生產(chǎn)環(huán)境下沒有使用到的樣式聲明

在您的 ?tailwind.config.js? 文件中,配置 ?purge ?選項指定所有的 pages 和 components 文件,使得 Tailwind 可以在生產(chǎn)構(gòu)建中對未使用的樣式進(jìn)行搖樹優(yōu)化。

// tailwind.config.js
  module.exports = {
    purge: [],
    purge: ['./index.html', './src/**/*.{vue,js,ts,jsx,tsx}'],
    darkMode: false, // or 'media' or 'class'
    theme: {
      extend: {},
    },
    variants: {
      extend: {},
    },
    plugins: [],
  }

在您的 CSS 中引入 Tailwind

創(chuàng)建 ?./src/index.css? 文件 并使用 ?@tailwind? 指令來包含 Tailwind的 ?base?、 ?components ?和 ?utilities ?樣式,來替換掉原來的文件內(nèi)容。

/* ./src/index.css */
@tailwind base;
@tailwind components;
@tailwind utilities;

Tailwind 會在構(gòu)建時將這些指令轉(zhuǎn)換成所有基于您配置的設(shè)計系統(tǒng)生成的樣式文件。

最后,確保您的 CSS 文件被導(dǎo)入到您的 ?./src/main.js? 文件中。

// src/main.js
import { createApp } from 'vue'
import App from './App.vue'
import './index.css'

createApp(App).mount('#app')

您已經(jīng)完成了所有步驟!現(xiàn)在,當(dāng)您運行 ?npm run dev?, Tailwind CSS 就可以在您的 Vue 3 and Vite 項目中使用了。


.red { background-color: red; }
以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號