react使用tailwind

现创建react项目

npx create-react-app name

进入创建的项目文件夹,安装tailwind,postcss,autoprefixer

因为react自带安装了上一版本的postcss,所以这里要特别指定安装对应的旧版本。

npm install -D tailwindcss@npm:@tailwindcss/postcss7-compat @tailwind/postcss7-compat postcss@^7 autoprefixer@^9

又由于react本身不让我们覆写它的postcss设定,所以要另外安装craco这个工具

npm i @craco/craco

下载完后,打开package.json文件,修改scripts中start,build,test的react-scripts为craco

在react中使用tailwind的问题

然后生成一个和package.json同级的craco.config.js,编写如下

module.exports = {
style: {
postcss: {
plugins: [
require('tailwindcss'),
require('autoprefixer')
]
}
}
}

这里的设定代表原先的postcss设定文件

然后

npx tailwindcss init`

初始化tailwind的设定文件tailwind.config.js,设定purge的数组为src的目录以及public文件夹下的index.html

    './src/**/*.{js,jsx,ts,tsx}',
'./public/index.html'

在react中使用tailwind的问题

然后编辑src目录下的index.css,清空里面的内容,然后加载tailwind三大部件。

@tailwind base;
@tailwind components;
@tailwind utilities;

到此为止,已经可以基本使用tailwind样式了,在App组件中尝试一下

import pic from './malibu.jpg'
function App() {
return (
<div className="antialiased text-gray-900 bg-gray-200 min-h-screen p-8 flex items-center flex-col justify-center min-w-screen">
<div className="p-4 bg-indigo-300 rounded-3xl ">
<h1 className=" text-xl font-semibold text-gray-500">Tailwind CSS</h1>
<div className="w-24 mt-3">
<img className="rounded-lg shadow-md" src={pic} alt="pic" />
</div>
<div className="">
<span className="float-left mt-2 p-2 bg-green-300 text-sm font-black rounded-full shadow-sm">Nice view!</span>
<div></div>
<span className=" mr-100% float-right mt-2 p-2 bg-white text-sm font-black rounded-full shadow-sm">Go now?</span>
</div>
</div>
</div>
);
}
export default App;

效果图

在react中使用tailwind的问题

以上为个人经验,希望能给大家一个参考,也希望大家多多支持本站。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。