🚀 Gatsby + React Native for Web + Expo 🥳

2025-06-05

🚀 Gatsby + React Native for Web + Expo 🥳

TL;DR: 🎳示例📚文档

替代文本

在这篇文章中,我将向您展示如何设置您的(通用)Expo 应用程序以在针对网络时使用Gatsby !

🚨 如果您发现错误,请在expo-cli repo上使用[gatsby]标题中的标签报告。

为什么要将 Gatsby 与 Expo 一起使用?

这样做的主要好处如下:

  • 您可以预渲染Expo应用程序的 Web 部分
  • 如果您已经使用 Gatsby,那么现在您可以在 Web 和移动设备之间共享大部分代码
  • 如果您是 Expo 新手,这也意味着您可以在浏览器中尽可能使用 Expo SDK 中的复杂浏览器功能,如相机、手势、权限等!

⚽️教程

替代文本

  • 安装或更新 Expo CLI:npm i -g expo-cli
  • 创建一个新的 Expo 项目:expo init
  • 安装 Gatsby 插件:
  # yarn
  yarn add gatsby gatsby-plugin-react-native-web

  # npm
  npm install --save gatsby gatsby-plugin-react-native-web
Enter fullscreen mode Exit fullscreen mode
   module.exports = {
     plugins: [
       `gatsby-plugin-react-native-web`,
       /* ... */
     ],
   }
Enter fullscreen mode Exit fullscreen mode
  • 添加/.cache/public到您的.gitignore
  • 现在创建 Gatsby 项目的第一页:
    • 创建页面文件夹:mkdir -p src/pages
    • 创建文件:
  # JS
  cp App.js src/pages/index.js

  # TS
  cp App.tsx src/pages/index.tsx
Enter fullscreen mode Exit fullscreen mode
  • 快去yarn gatsby develop尝试一下吧!
    • 在浏览器中打开项目http://localhost:8000/

替代文本

故障排除

如果您在没有 Expo CLI 的情况下启动了项目,您可能还需要执行以下操作:

  • 如果您使用 Gatsby CLI 启动了您的项目,请查看我在文档中编写的指南:使用 Expo 的 Gatsby 项目

  • 安装 React Native for Web:yarn add react-native-web

  • 为 React Native web 安装 babel 预设:

  # yarn
  yarn add --dev babel-preset-expo
  # npm
  npm install --save-dev babel-preset-expo
Enter fullscreen mode Exit fullscreen mode
  • 💡 尽管名称中包含 Expo,但您可以(并且应该)将其用于任何 React Native 项目,因为它提供了通用平台支持。
   module.exports = { presets: ['babel-preset-expo'] }
Enter fullscreen mode Exit fullscreen mode

🏁 新命令

  • 启动 Web

    • 🚫expo start:web
    • yarn gatsby develop
  • 构建网络

    • 🚫expo build:web
    • yarn gatsby build
  • 服务你的静态项目

    • 🚫serve web-build
    • yarn gatsby serve

📁 文件结构

这是支持 Gatsby 的 Expo 项目的推荐文件结构。

Expo Gatsby
├── src
│   └── pages ➡️ Routes
│       └── index.tsx ➡️ Entry Point for Gatsby
├── .cache ➡️ Generated Gatsby files (should be ignored)
├── public ➡️ Generated Gatsby files (should be ignored)
├── assets ➡️ All static assets for your project
├── App.tsx ➡️ Entry Point for Mobile apps
├── app.json ➡️ Expo config file
├── gatsby-config.js ➡️ Gatsby config file
└── babel.config.js ➡️ Babel config (should be using `babel-preset-expo`)
Enter fullscreen mode Exit fullscreen mode

👋 感谢阅读

希望这篇文章对你有帮助!如果你用过这个工作流程,我很想听听你的使用感受 😁 如果你没用过,我也很乐意听听!快来给我发个表情包吧 :]

📚 更多信息

文章来源:https://dev.to/evanbacon/gatsby-react-native-for-web-expo-2kgc
PREV
👑⚙️ Smaller, Faster Websites with Preact and Expo Before Preact After Preact ⚽️ Getting Started Drawbacks 👋 That's all
NEXT
Peregrine Rewrite - 类似 Python 的语言,速度与 C 语言一样快