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
相关产品推荐
相关产品推荐

