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

React与React Native同项目Web版本运行失败问题求助

Fixing Webpack Issues for React + React Native Shared Codebase

Hey there! Let's break down exactly what's causing your Web build to fail and fix it step by step. Looking at your error logs, there are two core problems:

1. Webpack is trying to resolve React Native-only modules in the Web environment

Errors like Can't resolve 'AppRegistry' or Can't resolve 'AppState' happen because these are Native-exclusive modules that don't exist in the browser. Your Web build is accidentally pulling in Native-side code (like src/native/routes/appNavigator.js), which depends on these modules.

2. react-native-elements isn't being transpiled by Babel

The "Unexpected token" errors in SearchBar.js, Card.js, etc., are because the react-native-elements source code uses untranspiled ES6+ features (like class properties and object rest/spread), but your current Webpack config excludes all node_modules from Babel processing.


Step 1: Install react-native-web for Web-compatible React Native modules

First, we need a way to map React Native core modules to Web-friendly equivalents. Install react-native-web:

npm install react-native-web --save

Step 2: Update Webpack Config to Handle Native-to-Web Aliasing

Modify your web.dev.config.js to add aliases and resolve extensions that prioritize Web-specific files:

const path = require('path')
const webpack = require('webpack')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const autoprefixer = require('autoprefixer')
const extractLess = new ExtractTextPlugin('css/style_webpack.css')

module.exports = {
  devtool: 'eval',
  entry: [path.resolve(__dirname, '../src/web/index')],
  cache: true,
  output: {
    path: path.join(__dirname, '../dist'),
    filename: 'bundle.js',
  },
  // Add this resolve section
  resolve: {
    alias: {
      // Map react-native to react-native-web for Web builds
      'react-native': 'react-native-web'
    },
    // Prioritize .web.js files over .native.js for Web
    extensions: ['.web.js', '.js', '.json', '.native.js']
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        // Exclude node_modules EXCEPT react-native-elements (needs transpilation)
        exclude: /node_modules\/(?!react-native-elements)/,
        loader: 'babel-loader',
        query: {
          plugins: [
            'transform-object-rest-spread',
            'transform-class-properties',
          ],
          presets: ['es2015', 'react', 'stage-0'],
        },
        include: path.resolve(__dirname, '../src')
      },
      {
        test: /\.less$/i,
        loader: extractLess.extract([
          {
            loader: 'raw-loader',
            options: { minimize: false, sourceMap: false },
          },
          {
            loader: 'postcss-loader',
            options: {
              plugins: () => [autoprefixer('>1%', 'ie 10')],
            },
          },
          {
            loader: 'less-loader',
            options: { strictMath: false, noIeCompat: true },
          },
        ]),
      },
    ],
  },
  plugins: [
    extractLess,
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify('development'),
        PLATFORM_ENV: JSON.stringify('web'),
      },
    }),
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoEmitOnErrorsPlugin(),
  ],
}

Step 3: Ensure Web Code Doesn't Import Native-Only Files

Your error log shows src/native/routes/appNavigator.js is being imported into your Web build. Fix this by:

  • Using environment-based conditional imports in shared code:
    if (process.env.PLATFORM_ENV === 'web') {
      import WebNavigator from './web/navigator';
    } else {
      import NativeNavigator from './native/navigator';
    }
    
  • Or using file suffix conventions: Rename Web-specific files to *.web.js and Native files to *.native.js. Webpack will automatically pick the right one thanks to the resolve.extensions we added earlier.

Step 4: Verify Dependencies

Double-check that all required Babel plugins are installed:

npm install babel-plugin-transform-object-rest-spread babel-plugin-transform-class-properties babel-preset-es2015 babel-preset-react babel-preset-stage-0 --save-dev

Why This Works

  • The react-native alias tells Webpack to use react-native-web instead of the real React Native core, which provides browser-compatible versions of modules like AppRegistry (though you should still avoid importing Native-only code in Web builds!).
  • Updating the exclude rule for Babel lets it transpile react-native-elements's unprocessed ES6+ code, fixing the "Unexpected token" errors.
  • The resolve extensions ensure Webpack prioritizes Web-specific files, preventing accidental Native code imports.

Give these changes a try, and your Web build should start working alongside your React Native app!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 06:59:27