🚀 Gatsby + React Native for Web + Expo 🥳
在这篇文章中,我将向您展示如何设置您的(通用)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
- 创建
gatsby-config.js
并使用插件:gatsby-config.js
module.exports = {
plugins: [
`gatsby-plugin-react-native-web`,
/* ... */
],
}
- 添加
/.cache
和/public
到您的.gitignore
- 现在创建 Gatsby 项目的第一页:
- 创建页面文件夹:
mkdir -p src/pages
- 创建文件:
- 创建页面文件夹:
# JS
cp App.js src/pages/index.js
# TS
cp App.tsx src/pages/index.tsx
- 快去
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
- 💡 尽管名称中包含 Expo,但您可以(并且应该)将其用于任何 React Native 项目,因为它提供了通用平台支持。
- 创建
babel.config.js
并使用 Babel 预设:babel.config.js
- 创建
module.exports = { presets: ['babel-preset-expo'] }
🏁 新命令
-
启动 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`)
👋 感谢阅读
希望这篇文章对你有帮助!如果你用过这个工作流程,我很想听听你的使用感受 😁 如果你没用过,我也很乐意听听!快来给我发个表情包吧 :]