前端工程化 -- 配置TailwindCss

本文提供两种在前端项目中配置TailwindCss的方法,希望能够帮助到被配置烦扰的同学。

1. 在CRA项目中配置tailwindcss

  1. eject前准备
csharp 复制代码
git init && git add . && git commit -m "init"
  1. 释放配置

    yarn eject

  2. 初始化tailwindcss的配置

csharp 复制代码
npx tailwindcss init
  1. 修改其中的配置
css 复制代码
content: ["./src/**/*.{ts,tsx,js,jsx}", "./public/index.html"],
  1. 引入tailwindcss的预置样式 在src/index.css文件头部增加:
less 复制代码
@tailwind base;
@taiwind components;
@tailwind utilities;
  1. 使用index.css 在src/index.tsx中引入index.css:
arduino 复制代码
import "./index.css";
  1. 测试 使用下面的代码测试是否配置成功:
css 复制代码
<div className="bg-blue-300 text-white p-4">Hello, Tailwind Css !</div>
  1. 运行项目
sql 复制代码
yarn start

2. 在非CRA项目中配置tailwindcss

  1. 使用webpack-cli快速生成基础配置
csharp 复制代码
yarn init -y
npx webpack init

选择"y",然后再次运行该命令。 2. 卸载自动安装的postcss和loader

arduino 复制代码
yarn remove postcss postcss-loader
  1. 安装tailwindcss及配套的postcss
sql 复制代码
yarn add postcss@8.4.4 postcss-flexbugs-fixes@5.0.2 postcss-loader@6.2.1 postcss-normalize@10.0.1 postcss-preset-env@7.0.1 tailwindcss@3.0.2
  1. 初始化tailwindcss配置项
csharp 复制代码
npx tailwindcss init
  1. 修改其中的配置
css 复制代码
content: ["./src/**/*.{ts,tsx,js,jsx}", "./index.html"],
  1. 创建样式文件
bash 复制代码
touch src/index.css
  1. 在样式文件中引入tailwindcss
less 复制代码
@tailwind base;
@taiwind components;
@tailwind utilities;
  1. 在src/index.ts中使用index.css
arduino 复制代码
import "./index.css";
  1. 在index.html中使用样式
css 复制代码
<div class="bg-blue-300 text-white p-4">Hello, Tailwind Css !</div>
  1. 修改webpack.config.js中的配置 替换postcss-loader的配置为:
javascript 复制代码
{
  loader: require.resolve('postcss-loader'),
  options:{
    postcssOptions:{
      ident: "postcss",
      config: false,
      plugins: !useTailWind ? [
        "postcss-flexbugs-fixes",
        ["postcss-preset-env", {
          autoprefixer: {flexbox: "no-2019"},
          stage: 3,
        }],
        "postcss-normalize",
      ]:[
        "tailwindcss",
        "postcss-flexbugs-fixes",
        ["postcss-preset-env", {
          autoprefixer: {flexbox: "no-2019"},
          stage: 3,
        }],
      ]
    }
  }
}

其中,const useTailWind = fs.existsSync(path.join("./", "tailwind.config.js")); 用于检查是否存在tailwind.config.js文件,以确定是否使用tailwindcss。 11. 测试

r 复制代码
yarn serve
yarn build:prod

以上是在CRA项目和非CRA项目中配置tailwindcss的步骤和代码示例。

相关推荐
风骏时光牛马6 小时前
生成一个移动端标题,只需要一个标题,不需要其他的任何文本。
前端
IT_陈寒6 小时前
Redis雪崩把我坑惨了,这是5年经验的教训
前端·人工智能·后端
SameX7 小时前
HarmonyOS ArkUI List 的侧滑删除 用 ListItem 的 swipeAction + endIcon 的做法
前端
usdoc文档预览9 小时前
USDOC系列之PPT文件在线编辑-VUE前端实现在线浏览器在线编辑PPT文档
前端·vue.js·编辑器·office365·ppt在线编辑·office文件在线编辑·文件在线编辑
用户2705077725249 小时前
Agent 调工具卡住?3 种超时与取消策略实测对比
前端
LuHang10 小时前
我一行代码没写,把领导派的活做成了公司内部系统😭
前端
明月_清风10 小时前
Meta 开源了一个 AI Native 组件库:Astryx,150+ React 组件,专为 AI Agent 而设计
前端·人工智能·ai编程
用户0873086548710 小时前
用 GUI 自动化写了一个群聊 AI:5 个真实事故,和 7 条让 AI 不像机器人的设计
node.js
用户8508692761510 小时前
秒杀系统中 Shell 脚本并发控制 Bug:究竟哪里出了
前端
程序员大阳12 小时前
HTML+CSS+JS对话式实战(3)-活动管理页实现查询、新增、删除API后端接口
javascript·css·html·实战·删除·查询·新增