第二章:项目搭建——create-expo-app + NativeWind

第二章:项目搭建——create-expo-app + NativeWind

“用 create-expo-app 跳过 90% 的原生配置,用 NativeWind 让移动端样式开发和 Web 一样直观。”


2.1 初始化项目

# 创建 Expo 项目
npx create-expo-app@latest my-app --template blank-typescript

# 进入项目
cd my-app

# 安装 NativeWind
npx expo install nativewind
npx expo install tailwindcss

# 初始化 shadcn-nativewind
npx shadcn-nativewind init

2.2 项目结构

my-app/
├── app/                      # Expo Router(文件系统路由)
│   ├── _layout.tsx          # 根布局
│   ├── index.tsx            # 首页
│   └── (auth)/              # 认证路由组
│       ├── login.tsx
│       └── register.tsx
├── components/
│   └── ui/                  # shadcn-nativewind 组件
├── lib/
│   ├── api.ts               # API 客户端
│   └── store.ts             # Zustand store
├── hooks/                   # 自定义 hooks
└── app.json                # Expo 配置

2.3 NativeWind 配置

flowchart
    A[tailwind.config.js] --> B[设计令牌]
    B --> C[颜色、字体]
    C --> D[NativeWind]
    D --> E[className]

2.4 API 客户端封装

// lib/api.ts
import * as SecureStore from "expo-secure-store"

const API_BASE = process.env.EXPO_PUBLIC_API_URL!

export async function apiRequest<T>(
  path: string,
  options: RequestInit = {}
): Promise<T> {
  const token = await SecureStore.getItemAsync("auth-token")

  const response = await fetch(`${API_BASE}${path}`, {
    ...options,
    headers: {
      "Content-Type": "application/json",
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
      ...options.headers,
    },
  })

  if (response.status === 401) {
    await SecureStore.deleteItemAsync("auth-token")
    throw new Error("UNAUTHORIZED")
  }

  if (!response.ok) {
    throw new Error(`HTTP ${response.status}`)
  }

  return response.json()
}

本章小结

  1. create-expo-app:快速初始化
  2. NativeWind:Tailwind for RN
  3. 目录结构:feature-based
  4. API 封装:统一错误处理

本章提示词模板

生成项目初始化

生成 Expo + React Native 项目初始化指南:

需求:
1. create-expo-app 命令
2. TypeScript 配置
3. NativeWind 安装和配置
4. shadcn-nativewind 安装
5. 目录结构设计

版本:Expo SDK 53, React Native 0.78

继续阅读:第三章:UI组件