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

React Native Web构建失败(Webpack相关错误)求助

React Native Web 构建错误(node_modules相关)解决建议

一、图片加载器缺失问题

  • 先安装对应loader:npm install file-loader --save-dev
  • 在webpack.config.js的module.rules中添加图片处理规则:
{
  test: /\.(png|jpe?g|gif|svg)$/i,
  use: [
    {
      loader: 'file-loader',
      options: {
        name: '[name].[ext]',
        outputPath: 'assets/images/',
      },
    },
  ],
}

如果用的是Webpack 5,也可以直接用内置的asset模块,不用额外装loader:

{
  test: /\.(png|jpe?g|gif|svg)$/i,
  type: 'asset/resource',
  generator: {
    filename: 'assets/images/[name].[ext]'
  }
}

二、模块找不到问题

  • 检查webpack.config.js的resolve配置,确保后缀和别名设置正确:
resolve: {
  extensions: ['.web.js', '.js', '.json', '.web.jsx', '.jsx'],
  alias: {
    'react-native$': 'react-native-web'
  }
}
  • 彻底清理依赖后重装:删除node_modules和package-lock.json,执行npm install

三、JSON文件被Babel错误解析问题

  • 修改Babel配置(.babelrc或babel.config.js),排除node_modules下的JSON文件,确保只处理需要转译的代码:
{
  "exclude": [/node_modules\/(?!(react-native-web|@react-native|react-native)\/).*/, /\.json$/],
  "presets": ["babel-preset-react-native-web"]
}
  • 或者在webpack.config.js里单独配置JSON的处理规则:
{
  test: /\.json$/,
  type: 'json/module',
  exclude: /node_modules/
}

四、通用排查要点

  • 确认react-native-web版本和react、react-dom版本兼容,比如react-native-web@0.19.x需要搭配react@18.x
  • 检查babel-loader配置,确保它能处理react-native-web相关模块,不要完全排除node_modules:
{
  test: /\.(js|jsx)$/,
  exclude: /node_modules\/(?!(react-native-web|@react-native|react-native)\/).*/,
  use: {
    loader: 'babel-loader',
    options: {
      presets: ['babel-preset-react-native-web']
    }
  }
}
  • 执行npm ls查看依赖树,排查是否存在版本冲突的包(比如多个版本的react或babel依赖)

内容的提问来源于stack exchange,提问作者Alejandro Sorto

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 16:40:26