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

React Native项目中twrnc结合Tailwind CSS类自动排序问题求助

修复twrnc中style属性的Tailwind类自动排序问题

针对你遇到的style={tw('...')}写法下Tailwind类排序失效、但class属性正常的问题,按以下步骤调整配置:

1. 配置Prettier插件识别twrnc语法

prettier-plugin-tailwindcss默认只处理class/className属性,需要明确告知插件识别twrnc的函数调用和style属性:

在你的Prettier配置文件(如.prettierrc、.prettierrc.js或package.json的prettier字段)中添加以下配置:

{
  "plugins": ["prettier-plugin-tailwindcss"],
  "tailwindFunctions": ["tw"],
  "tailwindAttributes": ["style"]
}

tailwindFunctions让插件解析tw()函数内的字符串,tailwindAttributes指定要处理的属性包含style。

2. 修正VSCode Tailwind CSS扩展的正则配置

你当前的experimental.classRegex存在语法错误,且未准确匹配tw('...')这种函数调用写法,替换为以下正则:

"tailwindCSS.experimental.classRegex": [
  "tw`([^`]*)", // tw`...`
  "tw\\(['\"]([^'\"]*)['\"]\\)", // tw('...') 或 tw("...")
  "tw={\\s*['\"]([^'\"]*)['\"]\\s*}", // <Component tw="..." />
  "tw\\.\\w+`([^`]*)", // tw.xxx`...`
  "tw\\(.*?\\)`([^`]*)" // tw(Component)`...`
]

同时保留tailwindCSS.classAttributes配置:

"tailwindCSS.classAttributes": ["class", "className", "style"]

3. 确保Tailwind配置覆盖所有目标文件

检查你的tailwind.config.js,确保content字段包含所有用到twrnc的React Native文件:

module.exports = {
  content: [
    "./App.{js,jsx,ts,tsx}",
    "./src/**/*.{js,jsx,ts,tsx}",
    // 根据你的项目结构补充路径
  ],
  // 其他配置...
}

4. 生效配置

  • 重启VSCode,确保所有配置变更加载
  • 手动触发一次格式化(快捷键Ctrl+Shift+I/Cmd+Shift+I)验证排序效果

内容的提问来源于stack exchange,提问作者RomanJuarez

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 23:05:33