【问题标题】:React router dom doesn't work with webpackReact 路由器 dom 不适用于 webpack
【发布时间】:2018-09-04 02:23:40
【问题描述】:

我正在使用 react-router v4。当我构建我的应用程序时,它似乎不再工作,并且在浏览器 URL 中总是出现根地址,如果我编写其他路由,如“/products”,它会尝试呈现此页面,但它总是重定向到主页。我想说,如果我按下应用程序内的按钮一切正常,但 URL 永远不会改变。

我在 react 路由器 redux 中进行了“推送”操作,但它仍然不起作用。我读过一些类似的问题,其中说我必须在我的 webpack 配置中添加一些东西,比如“historyApiFallback”,但没有任何效果。在其他部分说我必须添加'',但也不起作用。 Here说我必须使用react-router的'withRouter'方法,但是我应用了它并没有任何改变。

我正在使用 webpack 2.3.2、react-router-dom 4.0.0-beta.8 和 react-router-redux 5.0.0-alpha.4

那么,我做错了什么?

这里是我的 webpack 服务器配置:

const ExtractTextPlugin = require('extract-text-webpack-plugin');
const path = require('path');
const webpack = require('webpack');
const fs = require('fs');

var nodeModules = {
  "sendmail": "sendmail"
};

fs.readdirSync('node_modules')
  .filter(function(x) {
    return ['.bin'].indexOf(x) === -1;
  })
  .forEach(function(mod) {
    nodeModules[mod] = 'commonjs ' + mod;
  });

const config = {
  entry: ['babel-polyfill', path.join(__dirname, '../source/server.jsx')],
  output: {
    filename: 'index.js',
    path: path.join(__dirname, '../built/server'),
    publicPath: process.env.NODE_ENV === 'production' ? 'https://pos.lisapp.co:3001/' : 'http://localhost:3001/'
  },
  module: {
    rules: [
      {
        test: /\.json$/,
        use: 'json-loader',
      },
      {
        test: /\.jsx?$/,
        exclude: /(node_modules)/,
        loader: 'babel-loader',
        query: {
          presets: ['latest-minimal', 'react'],
          env: {
            production: {
              plugins: ['transform-regenerator', 'transform-runtime'],
              presets: ['es2015']
            },
            development: {
              presets: ['latest-minimal']
            }
          }
        },
      },
      {
        test: /\.css$/,
        exclude: /(node_modules)/,
        loader: 'css-loader/locals?modules'
      },
      {
        test: /\.css$/,
        exclude: /(node_modules|source)\/(?!(react-table)\/).*/,
        loader: 'css-loader/locals?modules'
      },
      {
        test: /\.css$/,
        exclude: /(node_modules|source)\/(?!(react-touch-screen-keyboard)\/).*/,
        loader: 'css-loader/locals?modules'
      },
      {
        test: /\.inline.svg$/,
        loaders: [ 'babel-loader',
          {
            loader: 'react-svg-loader',
            query: {
              svgo: {
                plugins: [{removeTitle: false}],
                floatPrecision: 2
              }
            }
          }
        ]
      },
      {
        test: /\.jpe?g$|\.gif$|\.png$|^(?!.*\.inline\.svg$).*\.svg$/,
        loader: 'url-loader?limit=400000'
      },
    ],
  },
  devtool: 'source-map',
  devServer: {
    historyApiFallback: true
  },
  externals: nodeModules,
  target: 'node',
  resolve: {
    extensions: ['.js', '.jsx', '.css', '.json'],
  },
  node: {
    fs: 'empty',
    dns: 'mock',
    net: 'mock',
    child_process: 'empty',
    tls: 'empty'
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
      }
    }),
    new webpack.optimize.OccurrenceOrderPlugin(true),
    new ExtractTextPlugin({
      filename: '../statics/styles.css',
      ignoreOrder: true,
    })
  ]
  // watch: true,
};

if (process.env.NODE_ENV === 'production') {
  config.plugins.push(
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
      mangle: {
        except: ['$super', '$', 'exports', 'require']
      }
    })
  );
}

module.exports = config;

这里是我的 webpack 客户端配置:

const ExtractTextPlugin = require('extract-text-webpack-plugin');
const path = require('path');
const webpack = require('webpack');

const config = {
  entry: ['babel-polyfill', path.join(__dirname, '../source/client.jsx')],
  output: {
    filename: 'app.js',
    path: path.join(__dirname, '../built/statics'),
    publicPath: process.env.NODE_ENV === 'production' ? 'https://pos.lisapp.co:3001/' : 'http://localhost:3001/'
  },
  module: {
    rules: [
      {
        test: /\.json$/,
        use: 'json-loader',
      },
      {
        test: /\.jsx?$/,
        exclude: /(node_modules)/,
        loader: 'babel-loader',
        query: {
          presets: ['es2016', 'es2017', 'react'],
          plugins: ['transform-es2015-modules-commonjs'],
          env: {
            production: {
              plugins: ['transform-regenerator', 'transform-runtime'],
              presets: ['es2015']
            },
            development: {
              plugins: ['transform-es2015-modules-commonjs']
            }
          }
        },
      },
      {
        test: /\.css$/,
        exclude: /(node_modules)/,
        loader: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: 'css-loader?modules',
        }),
      },
      {
        test: /\.css$/,
        exclude: /(node_modules|source)\/(?!(react-table)\/).*/,
        loader: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: 'css-loader',
        }),
      },
      {
        test: /\.css$/,
        exclude: /(node_modules|source)\/(?!(react-touch-screen-keyboard)\/).*/,
        loader: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: 'css-loader',
        }),
      },
      {
        test: /\.inline.svg$/,
        loader: 'babel-loader!react-svg-loader?' + JSON.stringify({
          svgo: {
            // svgo options
            plugins: [{removeTitle: false}],
            floatPrecision: 2
          }
        }),
      },
      {
        test: /\.jpe?g$|\.gif$|\.png$|^(?!.*\.inline\.svg$).*\.svg$/,
        loader: 'url-loader?limit=400000'
      },
    ],
  },
  devtool: 'source-map',
  devServer: {
    historyApiFallback: true
  },
  target: 'web',
  resolve: {
    extensions: ['.js', '.jsx', '.css', '.json'],
  },
  node: {
    fs: 'empty',
    dns: 'mock',
    net: 'mock',
    child_process: 'empty',
    tls: 'empty'
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify(process.env.NODE_ENV || 'development')
      }
    }),
    new webpack.optimize.OccurrenceOrderPlugin(true),
    new ExtractTextPlugin({
      filename: '../statics/styles.css',
      ignoreOrder: true,
    })
  ]
  // watch: true,
};

if (process.env.NODE_ENV === 'production') {
  config.plugins.push(
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
      mangle: {
        except: ['$super', '$', 'exports', 'require']
      }
    })
  );
}

module.exports = config;

【问题讨论】:

    标签: webpack react-router react-router-v4 react-router-dom


    【解决方案1】:

    对于面临同样问题的人来说,问题在于 babel 中使用的预设,因为 React Router v4 与 ES6 配合得更好。因此,在这种情况下,我们必须将 Uglify 插件更改为 this,并将其导入代码顶部,如下所示:

    const Uglify = require("uglifyjs-webpack-plugin");
    

    并更改这部分 Uglify 插件代码:

    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
      mangle: {
        except: ['$super', '$', 'exports', 'require']
      }
    })
    

    到这里:

    new Uglify({
      uglifyOptions: {
        ie8: false,
        ecma: 6,
        warnings: false
      }
    })
    

    您可以在此处进行更多优化,但对我来说这些是基本选项。

    此外,您可以将“路由”代码更改为 commonjs。希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-06
      • 1970-01-01
      • 2018-12-31
      • 2020-04-29
      • 1970-01-01
      • 2017-12-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多