You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Tailwind CSS样式转换为自定义类并写入CSS文件?解决@apply指令报错问题

如何将Tailwind CSS样式转换为自定义类并写入CSS文件?解决@apply指令报错问题

嘿,我来帮你搞定这个@apply报错的问题~你遇到的unknown rule at apply错误,本质是因为你的自定义CSS文件没被Tailwind的处理流程接管,浏览器和普通构建工具根本不认识@apply这个Tailwind专属语法。下面是一步步的解决办法,适配你用的Tailwind 3.4.1和React 18.2.0:


1. 确保你的CSS文件在Tailwind的处理链中

Tailwind的@apply是PostCSS插件提供的语法,必须让你的自定义CSS文件经过PostCSS + Tailwind的处理才行。

首先,打开你的app.css,要在开头先导入Tailwind的核心指令,再写你的自定义类:

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

.checkbox-style {
  @apply relative w-9 h-5 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600;
}

然后,一定要把这个app.css导入到你的React项目主入口文件里(比如src/index.js或者src/main.jsx),像这样:

import './app.css';
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';

// ... 其他项目初始化代码

2. 检查并修正tailwind.config.js配置

Tailwind需要知道哪些文件里用到了它的样式,这样才能正确生成对应的CSS。打开tailwind.config.js,确保content数组包含你的所有React组件文件,同时因为你用了dark:前缀,要把darkMode配置好:

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./src/**/*.{js,jsx,ts,tsx}", // 扫描所有React组件文件
    "./src/app.css" // 扫描你的自定义CSS文件
  ],
  darkMode: 'class', // 如果你是通过给根元素加dark类切换暗色模式就用这个;跟随系统设置则用'media'
  theme: {
    extend: {},
  },
  plugins: [],
}

3. 确认PostCSS配置(手动配置项目需注意)

如果你的项目是手动搭建的(不是Create React App、Vite这类脚手架自动生成的),要确保postcss.config.js里包含Tailwind和Autoprefixer插件:

module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
}

(脚手架生成的项目一般已经默认配置好,这一步可以跳过)


最后验证一下

做完上面的配置后,一定要重启你的开发服务器(热重载可能不会识别配置变更),然后把组件里的长className换成:

<div className="checkbox-style"></div>

(你的自定义类里已经包含了peer这个Tailwind类,不用额外添加啦)

这样应该就能正常渲染出你想要的开关样式,也不会再报@apply的错误了~

备注:内容来源于stack exchange,提问作者Charles

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.17 11:49:40