关于 migrate-nativewind-to-uniwind
这是一份将 React Native 项目从 NativeWind 迁移到 Uniwind 的操作指南,面向维护现有样式配置的开发者。它逐项说明依赖、Metro、CSS、主题及组件互操作的调整,并强调易遗漏的迁移细节。
主要功能
- 01迁移前检查配置与引用
- 02替换依赖并更新 Metro
- 03迁移 Tailwind 4 CSS 与主题
- 04用 withUniwind 替代互操作
- 05处理安全区域与类名冲突
- 06检查动画及残留引用
适用场景
- 01将现有应用从 NativeWind 切换到 Uniwind
- 02迁移自定义主题和 CSS 变量
- 03替换第三方组件的样式映射
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ uni-stack/ uniwind --skill migrate-nativewind-to-uniwind安装后在 Claude Code 中输入/migrate-nativewind-to-uniwind确认已加载。
详细介绍
将 NativeWind 迁移到 Uniwind
Uniwind 以更出色的性能和稳定性取代 NativeWind。它需要 Tailwind CSS 4,并使用基于 CSS 的主题,而非 JS 配置。
迁移前检查清单
开始前,请阅读项目现有的配置文件,了解当前设置:
package.json(NativeWind 版本、依赖项)tailwind.config.js/tailwind.config.tsmetro.config.jsbabel.config.jsglobal.css或同等作用的 CSS 入口文件nativewind-env.d.ts或nativewind.d.ts- 任何使用
nativewind中cssInterop或remapProps的文件 - 任何从
react-native-css-interop导入内容的文件 - 任何使用 NativeWind 的 ThemeProvider 的文件(使用
vars()的情况)
步骤 1:移除 NativeWind 和相关软件包
卸载以下所有软件包(如果存在):
npm uninstall nativewind react-native-css-interop
# or
yarn remove nativewind react-native-css-interop
# or
bun remove nativewind react-native-css-interop
重要:react-native-css-interop 是 NativeWind 的依赖项,必须移除。迁移时经常会漏掉它。请在整个代码库中搜索从该软件包导入内容的代码:
rg "react-native-css-interop" -g "*.{ts,tsx,js,jsx}"
移除找到的所有导入和用法。
步骤 2:安装 Uniwind 和 Tailwind 4
npm install uniwind tailwindcss@latest
# or
yarn add uniwind tailwindcss@latest
# or
bun add uniwind tailwindcss@latest
确保 tailwindcss 的版本为 4+。
步骤 3:更新 babel.config.js
移除 NativeWind 的 babel 预设:
// REMOVE this line from presets array:
// 'nativewind/babel'
Uniwind 不需要 babel 预设。
步骤 4:更新 metro.config.js
将 NativeWind 的 metro 配置替换为 Uniwind 的配置。withUniwindConfig 必须是最外层的封装器。
之前(NativeWind):
const { withNativeWind } = require('nativewind/metro');
module.exports = withNativeWind(config, { input: './global.css' });
之后(Uniwind):
const { getDefaultConfig } = require('expo/metro-config');
// For bare RN: const { getDefaultConfig } = require('@react-native/metro-config');
const { withUniwindConfig } = require('uniwind/metro');
const config = getDefaultConfig(__dirname);
module.exports = withUniwindConfig(config, {
cssEntryFile: './global.css',
polyfills: { rem: 14 },
});
cssEntryFile 必须是从项目根目录开始的相对路径字符串(例如 ./global.css 或 ./app/global.css)。
此选项不要使用绝对路径或 path.resolve(...) / path.join(...)。
// ❌ Broken
cssEntryFile: path.resolve(__dirname, 'app', 'global.css')
// ✅ Correct
cssEntryFile: './app/global.css'
始终将 polyfills.rem 设置为 14,以匹配 NativeWind 的默认 rem 值,并避免迁移后间距和尺寸出现差异。
如果项目使用了 light / dark 以外的自定义主题(例如通过 NativeWind 的 vars() 或自定义 ThemeProvider 定义的主题),请使用 extraThemes 注册这些主题。不要包含 light 或 dark,它们会自动添加:
module.exports = withUniwindConfig(config, {
cssEntryFile: './global.css',
polyfills: { rem: 14 },
extraThemes: ['ocean', 'sunset', 'premium'],
});
选项:
cssEntryFile(必填):CSS 入口文件的相对路径字符串(从项目根目录开始)polyfills.rem(迁移时必填):设置为14,以匹配 NativeWind 的 rem 基准值extraThemes(项目有自定义主题时必填):自定义主题名称数组——不要包含light/darkdtsFile(可选):生成的 TypeScript 类型文件路径,默认为./uniwind-types.d.tsdebug(可选):在开发期间记录不支持的 CSS 属性
步骤 5:更新 global.css
将 NativeWind 的 Tailwind 3 指令替换为 Tailwind 4 导入:
之前:
@tailwind base;
@tailwind components;
@tailwind utilities;
之后:
@import 'tailwindcss';
@import 'uniwind';
步骤 6:更新 CSS 入口导入
确保在主 App 组件(例如 App.tsx)中导入 global.css,而不是在注册应用的根 index.ts / index.js 中导入——在此处导入会导致热重载失效。
步骤 7:删除 NativeWind 类型定义
删除 nativewind-env.d.ts 或 nativewind.d.ts。Uniwind 会在 dtsFile 指定的路径自动生成自己的类型。
步骤 8:删除 tailwind.config.js
彻底移除 tailwind.config.js / tailwind.config.ts。所有主题配置都将使用 Tailwind 4 的 @theme 指令迁移到 CSS 中。
将自定义主题值迁移到 global.css:
之前(tailwind.config.js):
module.exports = {
theme: {
extend: {
colors: {
primary: '#00a8ff',
secondary: '#273c75',
},
fontFamily: {
normal: ['Roboto-Regular'],
bold: ['Roboto-Bold'],
},
},
},
};
之后(global.css):
@import 'tailwindcss';
@import 'uniwind';
@theme {
--color-primary: #00a8ff;
--color-secondary: #273c75;
--font-normal: 'Roboto-Regular';
--font-bold: 'Roboto-Bold';
}
字体系列必须指定单一字体——React Native 不支持字体回退。
步骤 9:移除所有 cssInterop 和 remapProps 用法
这是最容易遗漏的一步。 搜索整个代码库:
rg "cssInterop|remapProps" -g "*.{ts,tsx,js,jsx}"
将每个 cssInterop() / remapProps() 调用替换为 Uniwind 的 withUniwind():
之前(NativeWind):
import { cssInterop } from 'react-native-css-interop';
import { Image } from 'expo-image';
cssInterop(Image, { className: 'style' });
之后(Uniwind):
import { withUniwind } from 'uniwind';
import { Image as ExpoImage } from 'expo-image';
export const Image = withUniwind(ExpoImage);
withUniwind 会自动将 className 映射到 style,并映射其他常用属性。自定义属性映射:
const StyledProgressBar = withUniwind(ProgressBar, {
width: {
fromClassName: 'widthClassName',
styleProperty: 'width',
},
});
在模块级别定义包装后的组件(而不是在渲染函数内)。每个组件只应包装一次:
-
仅在一个文件中使用 — 在同一文件中定义包装后的组件:
// screens/ProfileScreen.tsx import { withUniwind } from 'uniwind'; import { BlurView as RNBlurView } from '@react-native-community/blur'; const BlurView = withUniwind(RNBlurView); export function ProfileScreen() { return <BlurView className="flex-1" />; } -
在多个文件中使用 — 在共享模块中包装一次并重新导出:
// components/styled.ts import { withUniwind } from 'uniwind'; import { Image as ExpoImage } from 'expo-image'; import { LinearGradient as RNLinearGradient } from 'expo-linear-gradient'; export const Image = withUniwind(ExpoImage); export const LinearGradient = withUniwind(RNLinearGradient);然后在所有需要的地方从共享模块导入:
import { Image, LinearGradient } from '@/components/styled';
绝不要在多个文件中对同一个组件调用 withUniwind — 包装一次,然后在所有地方导入。
重要:不要使用 withUniwind 包装来自 react-native 或 react-native-reanimated 的组件 — 它们本身就支持 className。这包括 View、Text、Image、ScrollView、FlatList、Pressable、TextInput、Animated.View 等。仅对第三方组件使用 withUniwind(例如 expo-image、expo-linear-gradient、@react-native-community/blur)。
重要 — 非样式颜色属性使用 accent- 前缀:React Native 组件具有 color、tintColor、backgroundColor 等属性,它们不属于 style 对象。若要通过 Tailwind 类设置这些属性,请在对应的 *ClassName 属性中使用 accent- 前缀:
// color prop → colorClassName with accent- prefix
<ActivityIndicator
className="m-4"
size="large"
colorClassName="accent-blue-500 dark:accent-blue-400"
/>
// color prop on Button
<Button
colorClassName="accent-background"
title="Press me"
/>
// tintColor prop → tintColorClassName with accent- prefix
<Image
className="w-6 h-6"
tintColorClassName="accent-red-500"
source={icon}
/>
规则:className 可接受用于样式属性的任何 Tailwind 工具类。对于非样式属性(color、tintColor 等),请使用带 accent- 前缀的 {propName}ClassName。这适用于所有内置的 React Native 组件。
步骤 10:迁移 NativeWind 主题变量
之前(使用 vars() 的 NativeWind JS 主题):
import { vars } from 'nativewind';
export const themes = {
light: vars({
'--color-primary': '#00a8ff',
'--color-typography': '#000',
}),
dark: vars({
'--color-primary': '#273c75',
'--color-typography': '#fff',
}),
};
// In JSX:
<View style={themes[colorScheme]}>
之后(Uniwind CSS 主题):
@layer theme {
:root {
@variant light {
--color-primary: #00a8ff;
--color-typography: #000;
}
@variant dark {
--color-primary: #273c75;
--color-typography: #fff;
}
}
}
重要:所有主题变体必须定义完全相同的一组 CSS 变量。如果 light 定义了 --color-primary 和 --color-typography,那么 dark(以及任何自定义主题)也必须定义这两个变量。变量不匹配会导致 Uniwind 运行时错误。
无需使用 ThemeProvider 包装器。从 JSX 中移除 NativeWind 的 <ThemeProvider> 或 vars() 包装器。如果使用了 React Navigation 的 <ThemeProvider>,请保留。
如果项目使用嵌套主题包装器来预览主题,或为特定子树强制设置主题(例如演示卡片、设置预览或并排主题对比),请使用 Uniwind Pro 的 ScopedTheme,而不是更改全局主题:
import { ScopedTheme } from 'uniwind';
<ScopedTheme theme="dark">
<PreviewCard />
</ScopedTheme>
如果项目有浅色/深色之外的自定义主题(例如 ocean、premium),则必须:
- 使用
@variant在 CSS 中定义这些主题:
@layer theme {
:root {
@variant ocean {
--color-primary: #0ea5e9;
--color-background: #0c4a6e;
}
}
}
- 通过
extraThemes在 metro.config.js 中注册这些主题(跳过light/dark— 它们会自动添加):
module.exports = withUniwindConfig(config, {
cssEntryFile: './global.css',
polyfills: { rem: 14 },
extraThemes: ['ocean', 'premium'],
});
步骤 11:迁移安全区域工具类
NativeWind 的安全区域类需要在 Uniwind 中显式设置:
import { SafeAreaProvider, SafeAreaListener } from 'react-native-safe-area-context';
import { Uniwind } from 'uniwind';
export default function App() {
return (
<SafeAreaProvider>
<SafeAreaListener
onChange={({ insets }) => {
Uniwind.updateInsets(insets);
}}
>
<View className="pt-safe px-safe">
{/* content */}
</View>
</SafeAreaListener>
</SafeAreaProvider>
);
}
步骤 12:验证 rem 值
NativeWind 使用 14px 作为 rem 基准值,Uniwind 默认使用 16px。步骤 4 已在 metro 配置中设置 polyfills: { rem: 14 },以保留 NativeWind 的间距。如果用户明确希望使用 Uniwind 的默认值(16px),可以移除 polyfill — 但要提醒他们,所有间距/尺寸都会发生变化。
第 13 步:处理 className 去重
Uniwind 不会自动对冲突的 className 去重(NativeWind 会)。如果代码库依赖 className={`p-4 ${overrideClass}`} 之类的覆盖模式,请设置一个 cn 工具函数。
首先,检查项目是否已有 cn 辅助函数(常见于 shadcn/ui 项目):
rg "export function cn|export const cn" -g "*.{ts,tsx,js}"
如果已有,请保持原样。如果没有,请安装依赖并创建:
npm install tailwind-merge clsx
创建 lib/cn.ts(或项目中存放工具函数的目录):
import { type ClassValue, clsx } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
用法:
import { cn } from '@/lib/cn';
<View className={cn('p-4 bg-white', props.className)} />
<Text className={cn('text-base', isActive && 'text-blue-500', disabled && 'opacity-50')} />
请使用 cn,不要直接使用 twMerge——它会先通过 clsx 处理条件类、数组和假值,再使用 tailwind-merge 去重。
Uniwind 也支持重要工具类。如果迁移的 NativeWind 代码有意使用 Tailwind 的 important 修饰符强制覆盖,请保留:
<View className="bg-blue-500 !bg-red-500" />
<Pressable className="bg-blue-500 active:!bg-red-500" />
对于同一个样式属性,重要工具类会覆盖非重要工具类。即使是重要的 className 工具类,内联 style 仍具有最高优先级。
第 14 步:更新动画类名
如果项目使用了 NativeWind 的 animated-* / 过渡类模式,请将其迁移为显式使用 react-native-reanimated。Uniwind OSS 不提供 NativeWind 风格的动画类行为。
请以本迁移指南章节为准:
第 15 步:清理剩余的 NativeWind 引用
最后检查——搜索并移除所有剩余引用:
rg "nativewind|NativeWind|native-wind" -g "*.{ts,tsx,js,jsx,json,css}"
检查以下内容:
- 任意文件中的 NativeWind 导入
package.json中的nativewind(包括 devDependencies)package.json中的react-native-css-interopbabel.config.js中的 NativeWind babel presetmetro.config.js中的 NativeWind metro wrappernativewind-env.d.ts或nativewind.d.ts文件- 任何
cssInterop()或remapProps()调用 - 从
nativewind导入的任何vars()
Uniwind API 与模式
useUniwind — 主题访问(变化时重新渲染)
文档:https://docs.uniwind.dev/api/use-uniwind
import { useUniwind } from 'uniwind';
const { theme, hasAdaptiveThemes } = useUniwind();
// theme: current theme name — "light", "dark", "system", or custom
// hasAdaptiveThemes: true if app follows system color scheme
适用于:在 UI 中显示主题名称、根据主题进行条件渲染、在主题变化时执行副作用。
Uniwind 静态 API — 主题访问(不重新渲染)
访问主题信息而不触发重新渲染:
import { Uniwind } from 'uniwind';
Uniwind.currentTheme // "light", "dark", "system", or custom
Uniwind.hasAdaptiveThemes // true if following system color scheme
适用于:日志记录、分析、渲染之外的命令式逻辑。
useResolveClassNames — 将 className 转换为样式对象
文档:https://docs.uniwind.dev/api/use-resolve-class-names
将 Tailwind 类转换为 React Native 样式对象。用于处理不支持 className 且无法使用 withUniwind 包装的组件(例如 react-navigation 主题配置):
import { useResolveClassNames } from 'uniwind';
const headerStyle = useResolveClassNames('bg-blue-500');
const cardStyle = useResolveClassNames('bg-white dark:bg-gray-900');
<Stack.Navigator
screenOptions={{
headerStyle: headerStyle,
cardStyle: cardStyle,
}}
/>
useCSSVariable — 在 JS 中访问 CSS 变量
文档:https://docs.uniwind.dev/api/use-css-variable
以编程方式获取 CSS 变量值。变量必须以 -- 为前缀,并且与 global.css 中定义的变量相匹配:
import { useCSSVariable } from 'uniwind';
const primaryColor = useCSSVariable('--color-primary');
const spacing = useCSSVariable('--spacing-4');
适用于:动画、第三方库配置、使用设计令牌进行计算。
CSS 函数 — 自定义工具类
文档:https://docs.uniwind.dev/api/css-functions
使用设备感知 CSS 函数(如 hairlineWidth()、fontScale()、pixelRatio())定义自定义工具类。这些函数可在任何位置使用(自定义 CSS 类、@utility 等),但不能用于 @theme {} 中(该规则仅接受静态值)。使用 @utility 创建可复用的 Tailwind 风格类:
@utility w-hairline { width: hairlineWidth(); }
@utility h-hairline { height: hairlineWidth(); }
@utility border-hairline { border-width: hairlineWidth(); }
@utility text-scaled { font-size: fontScale(); }
然后这样使用:<View className="w-hairline h-hairline" />
平台选择器
文档:https://docs.uniwind.dev/api/platform-select
使用 ios:、android:、web:、native: 前缀,按平台有条件地应用样式:
<View className="ios:bg-red-500 android:bg-blue-500 web:bg-green-500">
<Text className="ios:text-white android:text-white web:text-black">
Platform-specific styles
</Text>
</View>
主题切换
文档:https://docs.uniwind.dev/theming/basics
默认情况下,Uniwind 会遵循系统配色方案(自适应主题)。如需通过编程方式切换主题:
import { Uniwind } from 'uniwind';
Uniwind.setTheme('dark'); // force dark
Uniwind.setTheme('light'); // force light
Uniwind.setTheme('system'); // follow system (default)
Uniwind.setTheme('ocean'); // custom theme (must be in extraThemes)
ScopedTheme — 仅为子树设置主题
文档:https://docs.uniwind.dev/api/scoped-themes
当项目需要仅为部分 UI 设置不同主题(组件预览、主题化区域、嵌套演示),且不更改全局应用主题时,请使用 ScopedTheme:
import { ScopedTheme } from 'uniwind';
<View className="gap-3">
<PreviewCard />
<ScopedTheme theme="light">
<PreviewCard />
</ScopedTheme>
<ScopedTheme theme="dark">
<PreviewCard />
</ScopedTheme>
</View>
重要行为:
- 以最近的
ScopedTheme为准(支持嵌套作用域) useUniwind、useResolveClassNames和useCSSVariable等 Hook 会根据最近的作用域主题进行解析- 作用域内经
withUniwind包装的第三方组件也会从该作用域解析主题值 ScopedTheme可使用自定义主题名称(必须在extraThemes中定义)
根据主题设置样式 — 优先使用 CSS 变量
文档:https://docs.uniwind.dev/theming/style-based-on-themes
优先使用基于 CSS 变量的类,而不是显式的 dark:/light: 变体。 不要这样写:
// Avoid this pattern
<View className="light:bg-white dark:bg-black" />
定义 CSS 变量并直接使用:
@layer theme {
:root {
@variant light { --color-background: #ffffff; }
@variant dark { --color-background: #000000; }
}
}
// Preferred — automatically adapts to theme
<View className="bg-background" />
这种方式更简洁、更易于维护,而且也能自动适配自定义主题。
运行时更新 CSS 变量
文档:https://docs.uniwind.dev/theming/update-css-variables
在运行时更新主题变量,例如根据用户偏好或 API 响应进行更新:
import { Uniwind } from 'uniwind';
// Preconfigure theme based on user input or API response
Uniwind.updateCSSVariables('light', {
'--color-primary': '#ff6600',
'--color-background': '#1a1a2e',
});
仅当应用确实需要运行时主题功能时才应使用此模式(例如,用户选择的品牌颜色或由 API 驱动的主题)。
使用 tailwind-variants 的变体
文档:https://docs.uniwind.dev/tailwind-basics#advanced-pattern-variants-and-compound-variants
对于组件变体和复合变体,请使用 tailwind-variants 库:
import { tv } from 'tailwind-variants';
const button = tv({
base: 'px-4 py-2 rounded-lg',
variants: {
color: {
primary: 'bg-primary text-white',
secondary: 'bg-secondary text-white',
},
size: {
sm: 'text-sm',
lg: 'text-lg px-6 py-3',
},
},
});
<Pressable className={button({ color: 'primary', size: 'lg' })} />
Monorepo 支持
文档:https://docs.uniwind.dev/monorepos
如果项目是 monorepo,请在 global.css 中添加 @source 指令,让 Tailwind 扫描 CSS 入口文件所在目录之外的包(仅当该目录中有使用 Tailwind 类的组件时):
@import 'tailwindcss';
@import 'uniwind';
@source "../../packages/ui/src";
@source "../../packages/shared/src";
常见问题
文档:https://docs.uniwind.dev/faq
自定义字体:Uniwind 只会将 className 映射到 font-family,字体文件必须单独加载(在 app.json 中使用 expo-font 插件,或在裸 RN 项目中使用 react-native-asset)。@theme 中的字体系列名称必须与文件名完全一致(不含扩展名)。使用 @variant 设置各平台的字体(必须放在 @layer theme { :root { } } 内):
@layer theme {
:root {
@variant ios { --font-sans: 'SF Pro Text'; }
@variant android { --font-sans: 'Roboto-Regular'; }
@variant web { --font-sans: 'system-ui'; }
}
}
数据选择器:使用 data-[prop=value]:utility 根据属性设置样式。目前仅支持相等判断:
<View data-state={isOpen ? 'open' : 'closed'} className="data-[state=open]:bg-muted/50" />
Expo Router 中的 global.css 位置:将文件放在项目根目录,并在根布局(app/_layout.tsx)中导入。如果放在 app/ 中,外部组件需要使用 @source 指令。Tailwind 会从 global.css 所在位置开始扫描。
CSS 更改导致整个应用重新加载:Metro 无法对包含许多提供程序的文件进行热重载。将 global.css 的导入移至组件树更深处(例如导航根组件或主页)即可解决。
渐变:内置支持,无需额外依赖。使用 bg-gradient-to-r from-red-500 via-yellow-500 to-green-500。对于 expo-linear-gradient,使用 useCSSVariable 获取颜色——withUniwind 不适用,因为渐变属性是数组。
样式优先级:内联 style 始终会覆盖 className。静态样式使用 className,仅对真正动态的值使用内联样式。避免对同一属性混用两者。
序列化错误(Failed to serialize javascript object):清除缓存:watchman watch-del-all 2>/dev/null; rm -rf node_modules/.cache && npx expo start --clear。常见原因:复杂的 @theme 配置、循环 CSS 变量引用。
Metro unstable_enablePackageExports 冲突:某些应用(如 crypto)会禁用此功能,导致 Uniwind 无法正常工作。使用选择性解析器:
config.resolver.unstable_enablePackageExports = false;
config.resolver.resolveRequest = (context, moduleName, platform) => {
if (['uniwind', 'culori'].some((prefix) => moduleName.startsWith(prefix))) {
return context.resolveRequest({ ...context, unstable_enablePackageExports: true }, moduleName, platform);
}
return context.resolveRequest(context, moduleName, platform);
};
安全区域类:p-safe、pt-safe、pb-safe、px-safe、py-safe、m-safe、mt-safe 等。还支持 -or-{value}(最小间距)和 -offset-{value}(额外间距)变体。
Next.js:尚未获得官方支持。Uniwind 面向 Metro 和 Vite。社区插件:uniwind-plugin-next。对于 Next.js,请使用标准 Tailwind CSS 并共享设计令牌。
Vite:自 v1.2.0 起支持。将 uniwind/vite 插件与 @tailwindcss/vite 一起使用。
UI 套件:HeroUI Native、react-native-reusables 和 Gluestack 4.1+ 与 Uniwind 配合良好
已知问题与注意事项
- data- 属性*:Uniwind 支持
data-[prop=value]:utility语法以实现条件样式,类似于 NativeWind。 - 动画样式:将 NativeWind 动画类直接迁移到
react-native-reanimated。Uniwind Pro 内置了对 Reanimated 的支持。
验证
迁移后,请验证:
npx react-native start --reset-cache(清除 Metro 缓存),或在 expo 中运行npx expo start -c- 所有屏幕在 iOS 和 Android 上均能正确呈现
- 主题切换正常(浅色/深色)
- 自定义字体加载正常
- 安全区域内边距正确应用
- 控制台中没有有关缺失样式的警告
- 不再有来自
nativewind或react-native-css-interop的导入
重要:切勿猜测 Uniwind API。如果不确定任何 Uniwind API、钩子、组件或配置选项,请查阅并根据官方文档进行核实:https://docs.uniwind.dev/llms-full.txt