TailwindCSS 在 uniapp 中如何使用?
在 uniapp 项目中如何集成和使用 TailwindCSS?我按照官方文档配置后样式不生效,有没有完整的配置步骤或示例?需要注意哪些兼容性问题?
2 回复
在 uniapp 中使用 TailwindCSS:
- 安装依赖:
npm install -D tailwindcss postcss autoprefixer
- 创建配置文件:
npx tailwindcss init
- 在
tailwind.config.js中配置:
module.exports = {
content: ['./src/**/*.{vue,js,ts}'],
// 其他配置
}
- 在
App.vue中引入样式:
@tailwind base;
@tailwind components;
@tailwind utilities;
- 在页面中直接使用 class 即可,如:
class="flex p-4"
在 UniApp 中使用 TailwindCSS 需要手动配置,因为 UniApp 默认不支持。以下是具体步骤:
1. 安装 TailwindCSS
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init
2. 配置 tailwind.config.js
module.exports = {
content: ["./src/**/*.{vue,js,ts,jsx,tsx}"],
theme: {
extend: {},
},
plugins: [],
}
3. 创建 CSS 文件
在 src 目录新建 tailwind.css:
@tailwind base;
@tailwind components;
@tailwind utilities;
4. 配置 vue.config.js
const path = require('path')
module.exports = {
configureWebpack: {
module: {
rules: [
{
test: /\.css$/,
use: [
'style-loader',
'css-loader',
{
loader: 'postcss-loader',
options: {
postcssOptions: {
plugins: [
require('tailwindcss')({
config: path.resolve(__dirname, 'tailwind.config.js')
}),
require('autoprefixer')
]
}
}
}
]
}
]
}
}
}
5. 在 main.js 中引入
import '@/tailwind.css'
使用示例
<template>
<view class="bg-blue-500 text-white p-4 rounded">
Hello TailwindCSS
</view>
</template>
注意事项:
- 某些 Tailwind 类可能需要额外配置才能兼容小程序
- 建议使用
@apply提取常用样式减少包体积 - 生产环境需开启 PurgeCSS 移除未使用样式
完成配置后即可在 Vue 文件中使用 Tailwind 的原子化类名。

