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

ViteJS生产构建预览时出现'null is not an object (evaluating 'yt.current.useState')'错误

React Native Web + Vite 生产预览报错:null is not an object (evaluating 'yt.current.useState')

问题场景

使用Yarn Workspaces搭建双环境:React Native原生环境、Vite+React+React Native Web环境。开发模式下运行正常,但执行yarn workspaces web build(等价vite build)编译成功后,运行yarn workspaces web preview(等价vite preview)时触发如下错误:

null is not an object (evaluating 'yt.current.useState')

当前vite.config.ts配置

// vite.config.ts

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react-swc'

const extensions = [
  ".web.tsx",
  ".tsx",
  ".web.ts",
  ".ts",
  ".web.jsx",
  ".jsx",
  ".web.js",
  ".js",
  ".css",
  ".json",
];

const development = process.env.NODE_ENV === "development";

export default defineConfig({
  clearScreen: true,
  plugins: [react()],
  define: {
    // https://github.com/bevacqua/dragula/issues/602#issuecomment-1296313369
    global: "window",
    __DEV__: JSON.stringify(development),
    // https://tamagui.dev/docs/intro/installation
    DEV: JSON.stringify(development),
    "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV),
  },
  envDir: "../../",
  optimizeDeps: {
    esbuildOptions: {
      resolveExtensions: extensions,
      jsx: "automatic",
      loader: { ".js": "jsx" }
    }
  },
  resolve: {
    extensions,
    alias: {
      'react-native': 'react-native-web'
    }
  }
})

已做排查动作

  • 更新所有依赖包,确保React/React Native版本完全匹配
  • 参考相关社区讨论调整过vite.config.ts配置

可行解决方向

1. 优化生产打包配置

在Vite的build选项中添加针对React Native Web的兼容配置,避免Rollup打包时的模块解析错误:

export default defineConfig({
  // ...原有配置
  build: {
    commonjsOptions: {
      include: [/react-native-web/, /node_modules/]
    },
    rollupOptions: {
      output: {
        manualChunks: undefined // 禁用代码分割,避免React上下文丢失
      }
    }
  }
})

2. 替换SWC插件为Babel插件

@vitejs/plugin-react-swc在生产打包时对React Native Web的兼容性可能存在问题,切换回Babel插件尝试:

  • 卸载SWC插件:yarn remove @vitejs/plugin-react-swc
  • 安装Babel插件:yarn add @vitejs/plugin-react -D
  • 修改vite.config.ts:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react' // 替换为Babel版插件
// ...其余配置不变

3. 调整依赖预构建规则

在optimizeDeps中明确指定预构建React Native Web,避免生产环境下的模块异常:

optimizeDeps: {
  include: ['react-native-web'],
  esbuildOptions: {
    resolveExtensions: extensions,
    jsx: "automatic",
    loader: { ".js": "jsx" }
  }
}

4. 修正全局变量定义

生产环境下global直接指向window可能引发冲突,调整为环境区分的定义:

define: {
  __DEV__: JSON.stringify(development),
  DEV: JSON.stringify(development),
  "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV),
  global: development ? "window" : "globalThis"
}

内容的提问来源于stack exchange,提问作者Fabio Dijkshoorn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 16:30:03