React Native 项目打包为 Web 版本

文章目录

    用 React Native 开发了一个聊天的 APP,想同时支持 App 和 Web 版本。
    之前一直以为 React Native 只能开发 Android 和 iOS 版本的 APP,没想到还能直接打包为 Web 版本。(当然微软也提供了 Windows 客户端版本的支持)

    Web 版本打包命令

    npx expo export
    

    可以看到输出如下:

    Starting Metro Bundler
    iOS Bundled 40778ms node_modules\expo-router\entry.js (1170 modules)
    Android Bundled 44507ms node_modules\expo-router\entry.js (1172 modules)
    Static rendering is enabled. Learn more: https://docs.expo.dev/router/reference/static-rendering/
    λ Bundled 31900ms node_modules\expo-router\node\render.js (937 modules)
    Web Bundled 32427ms node_modules\expo-router\entry.js (916 modules)
    Web node_modules\expo-router\entry.js 100.0% (916/916)[Reanimated] useAnimatedKeyboard is not available on web yet.
    [Reanimated] useAnimatedKeyboard is not available on web yet.
    
    › ios bundles (1):
    _expo/static/js/ios/entry-2cc0a6147605affd36fdffb16da4a350.hbc (3.48 MB)
    
    › android bundles (1):
    _expo/static/js/android/entry-99de2f8c7737324ffb0b5ff5f0c30cbb.hbc (3.53 MB)
    
    › web bundles (1):
    _expo/static/js/web/entry-b22c981170330af069ced8ec184c502b.js (1.62 MB)
    
    › Static routes (6):
    / (index) (24.5 kB)
    /explore (27.6 kB)
    /_sitemap (25.8 kB)
    /+not-found (22.6 kB)
    /(tabs) (24.5 kB)
    /(tabs)/explore (27.6 kB)
    
    Exported: dist
    

    导出的目录为 dist。

    唯一的遗憾就是打包的体积比较大,1M 多,后续看看是否可以优化。

    本地体验

    cd dist
    npx serve
    

    然后会看到如下输出:

    Need to install the following packages:
    serve@14.2.4
    Ok to proceed? (y) y
    
    
       ┌────────────────────────────────────────────┐
       │                                            │
       │   Serving!                                 │
       │                                            │
       │   - Local:    http://localhost:3000        │
       │   - Network:  http://192.168.31.166:3000   │
       │                                            │
       │   Copied local address to clipboard!       │
       │                                            │
       └────────────────────────────────────────────┘
    

    用浏览器打开:

    http://localhost:3000

    就能看到效果了。

    感想

    还是得看看 Expo 的官方文档。(这两天在手机上大致浏览了一遍)
    因为很多查到的资料都过时了,只有官方文档是比较新的方式。

    参考

    https://blog.logrocket.com/complete-guide-react-native-web/

    废弃的方案

    > npx expo export:web
    CommandError: expo export:web can only be used with Webpack. Use expo export for other bundlers.
    
    > npx expo install @expo/webpack-config
    Hey! I believe Webpack is being deprecated in 49, you'll have to switch to the Metro bundler on Web
    

    因为 expo 最新版本已经内置了 web 版本的打包功能,所以不再需要 webpack config 了。

    阅读更多 👀

    React Native 跨平台应用开发教程

    关于作者 🌱

    我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊,或者关注我的个人公众号“大象工具”, 查看更多联系方式