前言
vue2项目按官方的命令行执行,很容易不生效或者报一推莫名其妙的错误,这些其实都是版本的兼容问题引起的。所以在安装依赖时需指明版本!
这问题也让我走了不少坑,为了让大家少走些弯路,专门花时间整了这篇文章,希望对大家能有帮助。
安装依赖
npm install tailwindcss@npm:@tailwindcss/postcss7-compat @tailwindcss/postcss7-compat postcss@^7
配置
在项目根目录的postcss.config.js
(没有的话创建),添加以下内容:
module.exports = {plugins: {tailwindcss: {},},
};
在根目录的vue.config.js
添加css配置:
module.exports = defineConfig({css: {loaderOptions: {postcss: {postcssOptions: {plugins: [require('tailwindcss'),]}}}},
})
在根目录中tailwind.config.js
进行自定义设置 (可选):
例如自定义一个名cyan
的主题色,值为#9cdbff
module.exports = {theme: {extend: {colors: {cyan: '#9cdbff',}}},variants: {},plugins: []
}
这部分可配置内容还有很多,具体可以看官网的配置说明。
使用
创建tailwind.css
,并在项目(入口文件)中引入
@tailwind base;
@tailwind components;
@tailwind utilities;/* 自定义组件类 */
@layer components {.btn-primary {@apply py-2 px-4 bg-blue-500 text-white rounded-md hover:bg-blue-600 text-center;}.my-class{@apply bg-red-500;}
}
测试
写一个简单的例子进行测试效果
<template><div><h1 class="my-class text-4xl text-green-700 text-center font-semibold">Hello Tailwind</h1><div class="btn-primary">按钮</div></div>
</template>
<script>
export default {
}
</script>