试了几个方法,还是这种好用一点
STEP 1:安装相关依赖
npm install -D tailwindcss postcss autoprefixer weapp-tailwindcss
STEP 2:补充配置
# 初始化 tailwind.config.js 文件
npx tailwindcss init
执行上面命令生成tailwind.config.js,并增加如下配置
/** @type {import('tailwindcss').Config} */
module.exports = {
// 不在 content 包括的文件内编写的 class,不会生成对应的工具类
content: ['./public/index.html', './src/**/*.{html,js,ts,jsx,tsx,vue}'],
// 其他配置项
// ...
corePlugins: {
// 不需要 preflight,因为这主要是给 h5 的,如果你要同时开发小程序和 h5 端,你应该使用环境变量来控制它
preflight: false
}
}
手动创建postcss.config.js,并注册Tailwindcss
// postcss.config.js
// 假如你使用的框架/工具不支持 postcss.config.js,则可以使用内联的写法
// 其中 `autoprefixer` 有可能已经内置了,假如框架内置了可以去除
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
}
}
在项目的配置文件 config/index中注册weapp-tailwindcss:
// config/index.js
const { UnifiedWebpackPluginV5 } = require('weapp-tailwindcss/webpack')
{
mini: {
webpackChain(chain, webpack) {
chain.merge({
plugin: {
install: {
plugin: UnifiedWebpackPluginV5,
args: [{
appType: 'taro'
}]
}
}
})
}
}
}
另外在和 @tarojs/plugin-html 一起使用时,需要配置下 postcss-html-transform 这个插件,不然默认配置下它会移除整个 Tailwindcss 注入的 css var 区域块,这会造成所有 tw-* 相关变量找不到,导致样式大量挂掉的问题。
// config/index.js
config = {
// ...
mini: {
// ...
postcss: {
htmltransform: {
enable: true,
// 设置成 false 表示 不去除 * 相关的选择器区块
// 假如开启这个配置,它会把 tailwindcss 整个 css var 的区域块直接去除掉
// 需要用 config 套一层,官方文档上是错的
config: {
removeCursorStyle: false,
}
},
},
},
}
STEP 3:在项目入口引入Tailwindcss
|
这样就可以愉快的在 taro项目中使用Tailwindcss开发需求了。