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

如何在Expo创建的React Native项目中集成Tailwind/Nativewind并配置Babel?

关于Expo项目中添加Nativewind及Babel配置的问题解答

1. 如何在Expo项目中添加Nativewind CSS

Nativewind是Tailwind CSS在React Native中的适配方案,操作步骤如下:

  • 安装依赖包:
    npm install nativewind
    npm install --save-dev tailwindcss@3.3.2 postcss
    
  • 初始化Tailwind配置文件:
    npx tailwindcss init -p
    
  • 修改tailwind.config.js,指定需要扫描的组件文件路径:
    /** @type {import('tailwindcss').Config} */
    module.exports = {
      content: [
        "./App.{js,jsx,ts,tsx}",
        "./src/**/*.{js,jsx,ts,tsx}"
      ],
      theme: {
        extend: {},
      },
      plugins: [],
    }
    
  • 修改Babel配置(无论现有配置是.json还是手动创建.js,核心配置一致):
    若项目默认是babel.config.json,修改为:
    {
      "presets": ["babel-preset-expo"],
      "plugins": ["nativewind/babel"]
    }
    
    若手动创建babel.config.js,内容如下:
    module.exports = function(api) {
      api.cache(true);
      return {
        presets: ['babel-preset-expo'],
        plugins: ['nativewind/babel'],
      };
    };
    
  • 在项目入口文件(如App.js)中导入Nativewind样式:
    import 'nativewind/css';
    
  • 完成以上步骤后,即可在组件中使用Tailwind类名:
    <View className="flex-1 justify-center items-center bg-blue-500">
      <Text className="text-white text-2xl">Hello Nativewind</Text>
    </View>
    

2. npx create-expo-app@latest是否默认包含babel.config.js?

从Expo SDK 50版本开始,create-expo-app默认生成的是babel.config.json文件,而非.js格式,这就是你找不到.babel.config.js的原因。

如果需要手动创建babel.config.js,直接在项目根目录新建该文件,基础配置如下:

module.exports = function(api) {
  api.cache(true);
  return {
    presets: ['babel-preset-expo'],
    plugins: [],
  };
};

如果是为Nativewind配置,只需在plugins数组中添加'nativewind/babel'即可,具体参考第一部分的配置示例。

注意:若项目中同时存在babel.config.json和babel.config.js,Expo会优先读取.js文件,按需保留其中一个即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 19:15:02