weapp-tailwindcss:文档链接
一、CLI创建uniapp
npx degit dcloudio/uni-preset-vue#vite-ts my-vue3-project
npm install
npm run dev:h5
二、 安装TailwindCss3
npm install tailwindcss@3 postcss autoprefixer -D
三、初始化
- 初始化TailwindCss、postcss,生成
tailwind.config.js、postcss.config.js
npx tailwindcss init -p
tailwind.config.js
/** @type {import('tailwindcss').Config} */
module.exports = {
// 配置需要扫描的文件类型--即src下的所有vue、js、ts文件
content: ['./public/index.html', './src/**/*.{html,js,ts,vue}'],
// 自定义拓展配置
theme: {
// 覆盖默认配置
colors: {
'blue': '#3c9cff',
'purple': '#7e5bef',
'pink': '#ff49db',
'orange': '#ff7849',
'green': '#41B883',
'yellow': '#ffc82c',
'gray-dark': '#273444',
'gray': '#8492a6',
'gray-light': '#d3dce6',
},
// 新增额外配置
extend: {
// 扩展颜色
colors: {
'purple-pink': '#8135f5',
'blue-light': '#9acafc'
},
},
},
// 配置插件
plugins: [
// 示例:自定义按钮样式:btn-primary <button class="btn-primary">点击我</button>
function({ add***ponents }) {
add***ponents({
'.btn-primary': {
'@apply bg-blue text-[#fff] font-bold rounded': '',
'&:hover': {
'@apply bg-blue-light' : '',
}
}
})
},
],
// ...
corePlugins: {
// 小程序不需要 preflight,因为这主要是给 h5 的,如果你要同时开发小程序和 h5 端,你应该使用环境变量来控制它
preflight: false
}
}
postcss.config.js
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
四、引用TailwindCss
在uniapp的App.vue文件:
<style>
@tailwind base;
@tailwind ***ponents;
@tailwind utilities;
</style>
五、安装weapp-tailwindcss
npm install weapp-tailwindcss -D
注意:如果tailwindcss 在 weapp-tailwindcss 之后安装,可以手动执行一下 patch 方法,npx weapp-tw patch
在package.json文件:
"scripts": {
// 用于rpx单位支持和上下文通信
"postinstall": "weapp-tw patch"
}
六、注册插件
在vite.config.ts文件:
import { defineConfig } from "vite";
import uni from "@dcloudio/vite-plugin-uni";
import { UnifiedViteWeappTailwindcssPlugin as uvwt } from 'weapp-tailwindcss/vite';
export default defineConfig({
// uni 是 uni-app 官方插件, uvtw 一定要放在 uni 后,对生成文件进行处理
plugins: [uni(),uvwt()],
css: {
postcss: {
plugins: [
// require('tailwindcss')() 和 require('tailwindcss') 等价的,表示什么参数都不传,如果你想传入参数
// require('tailwindcss')({} <- 这个是postcss插件参数)
require('tailwindcss'),
require('autoprefixer')
],
},
},
});
七、使用TailwindCss
<template>
<view class="flex flex-col items-center justify-center h-screen">
<image alt="Vue logo" src="@/static/logo.png" class="w-[200rpx] h-[200rpx]" />
<view class="font-[600] text-[40rpx] my-3 flex items-center flex-wrap justify-center">
<text class="text-green">vue 3</text>+
<text class="text-blue">vite</text>+
<text class="text-orange">typescript</text> +
<text class="text-purple-pink">tailwindcss4</text>
</view>
<button class="btn-primary">点击我</button>
</view>
</template>