开发者问题收集

React Webpack 在生产中出现错误 #105

2017-05-12
1604

我有点绝望了。

我正在开发一个 React 应用程序并使用 webpack 来编译我的 bundle.js。 问题是,当我尝试将其编译用于“生产”时,我最终遇到了一个非常严重的错误:

“最小化的 React 错误 #105;访问 http://facebook.github.io/react/docs/error-decoder.html?invariant=105&args[]=HardwareKeyboardArrowDown 获取完整消息,或使用非最小化的开发环境获取完整错误和其他有用的警告。”

随后是一堆 “未捕获的类型错误:无法读取 null 的属性‘__reactInternalInstance$qw6tjofxg1o’”

当我将 node.env 设置为开发时('NODE_ENV': JSON.stringify('developement') ),它工作正常。

错误中的链接显示:“必须返回一个有效的 React 元素(或 null)。您可能返回了未定义的、数组或其他无效对象”但我在开发模式下没有任何问题,所以我不认为它来自我的代码,而且我找不到应该在哪里解决这个问题,因为开发模式没有告诉我更多信息……

这是我的 webpack 配置 & package.json :

const webpack = require('webpack');
const path = require('path');
const buildPath = path.resolve(__dirname, 'build');
const nodeModulesPath = path.resolve(__dirname, 'node_modules');
const TransferWebpackPlugin = require('transfer-webpack-plugin');

const config = {
    entry: [
    './src/app/app.js'
  ],
  // Render source-map file for final build
  devtool: 'source-map',
  debug: true,
  // output config
  output: {
    path: path.join(__dirname, 'public'),
    filename: 'bundle.js',
    publicPath: '/public/'
  },

  plugins: [
    // Define production build to allow React to strip out unnecessary checks
    new webpack.DefinePlugin({
      'process.env':{
        'NODE_ENV': JSON.stringify('production')
      }
    }),

    // Minify the bundle
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        // suppresses warnings, usually from module minification
        warnings: false,
      },
    }),
    // Allows error warnings but does not stop compiling.
    new webpack.NoErrorsPlugin(),
    // Transfer Files

  ],
  module: {
    loaders: [
      {
        test: /\.js$/, // All .js files
        loaders: ['babel-loader'], // react-hot is like browser sync and babel loads jsx and es6-7
        exclude: [nodeModulesPath],
      },
       {
        test: /\.css$/,
        loader: 'style-loader!css-loader',
        include: /flexboxgrid/
      },
      {
        test: /\.json$/, loader: "json-loader",
      },
      { test: /\.scss?$/,
        loader: 'style!css!sass',
        include: path.join(__dirname, 'src', 'styles') },
      { test: /\.png$/,
        loader: 'file' },
      { test: /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9]+)?$/,
        loader: 'file'}
    ],

    resolve: {
      extensions: ['', '.js', '.jsx', '.css', '.json']
  }
  },
};

module.exports = config;

{
  "name": "material-ui-example-webpack",
  "version": "0.16.0",
  "description": "Sample project that uses Material-UI",
  "repository": {
    "type": "git",
    "url": "https://github.com/callemall/material-ui.git"
  },
  "scripts": {
    "start": "webpack-dev-server --config webpack-dev-server.config.js --host $IP --port $PORT  --hot --progress --inline --colors",
    "clean-public": "npm run remove-public && mkdir public",
    "remove-public": "node_modules/.bin/rimraf ./public",
    "build:html": "babel-node tools/buildHtml.js",
    "heroku-prebuild": "npm install && npm-run-all clean-public build:html",
    "heroku-postbuild": "babel-node tools/build.js",
    "prod-start": "babel-node tools/publicServer.js"
  },
  "private": true,
  "devDependencies": {
    "babel-core": "^6.18.2",
    "babel-loader": "^6.2.8",
    "babel-preset-es2015": "^6.18.0",
    "babel-preset-react": "^6.16.0",
    "babel-preset-stage-2": "^6.18.0",
    "html-webpack-plugin": "^2.24.1",
    "npm-run-all": "1.8.0",
    "redux-devtools": "^3.4.0",
    "redux-devtools-dock-monitor": "^1.1.2",
    "redux-devtools-log-monitor": "^1.3.0",
    "rimraf": "2.5.2",
    "transfer-webpack-plugin": "^0.1.4",
    "webpack": "^1.13.3",
    "webpack-dev-server": "^1.16.2"
  },
  "dependencies": {
    "axios": "^0.16.1",
    "babel-cli": "6.8.0",
    "babel-loader": "^6.2.8",
    "babel-polyfill": "6.8.0",
    "babel-preset-es2015": "6.6.0",
    "babel-preset-react": "6.5.0",
    "babel-preset-stage-2": "^6.24.1",
    "cheerio": "^0.20.0",
    "colors": "1.1.2",
    "compression": "^1.6.1",
    "css-loader": "^0.27.3",
    "express": "^4.15.2",
    "json-loader": "^0.5.4",
    "lint": "^1.1.2",
    "material-ui": "^0.17.1",
    "ncp": "^2.0.0",
    "npm-run-all": "1.8.0",
    "open": "0.0.5",
    "react": "^15.4.1",
    "react-component-queries": "^2.1.1",
    "react-dom": "^15.4.1",
    "react-fittext": "https://github.com/gianu/react-fittext",
    "react-flexbox-grid": "^1.0.2",
    "react-html-parser": "^1.0.3",
    "react-masonry-component": "^5.0.5",
    "react-redux": "^5.0.4",
    "react-responsive": "^1.2.7",
    "react-router": "^2.0.0-rc5",
    "react-router-dom": "^4.0.0",
    "react-sizeme": "^2.3.1",
    "react-tap-event-plugin": "^2.0.1",
    "redux": "^3.6.0",
    "redux-form": "^6.6.3",
    "redux-promise": "^0.5.3",
    "rimraf": "2.5.2",
    "serve-favicon": "^2.3.0",
    "style-loader": "^0.16.0",
    "transfer-webpack-plugin": "^0.1.4",
    "webpack": "^1.13.3"
  }
}

buildHtml 脚本 :

import fs from 'fs';  
import cheerio from 'cheerio';  
import colors from 'colors';

/*eslint-disable no-console */
console.log("buildHTML.js start");
fs.readFile('src/index.html', 'utf8', (err, markup) => {  
  if (err) {
    return console.log(err);
  }

  const $ = cheerio.load(markup);
  $('head').prepend('');

  fs.writeFile('public/index.html', $.html(), 'utf8', function (err) {
    if (err) {
      return console.log(err);
    }
    console.log('index.html written to /public'.green);
  });
});

然后是 build.js

/*eslint-disable no-console */
import webpack from 'webpack';  
import webpackConfig from '../webpack-production.config';  
import colors from 'colors';
import ncp from 'ncp';

process.env.NODE_ENV = 'production'; 
console.log("build.js start");
//Static files to import in /public (images/css)
var source = [["src/images","public/images"],["src/css","public/css"]];

function copyStaticFiles(path){
    ncp(path[0], path[1], function (err) {
  if (err) {
     return console.error(err);
  }})
}

console.log('Generating minified bundle for production via Webpack...'.blue);

webpack(webpackConfig).run((err, stats) => {  

  if (err) { // so a fatal error occurred. Stop here.
    console.log(err.bold.red);
    return 1;
  }

  const jsonStats = stats.toJson();

  if (jsonStats.hasErrors) {
    return jsonStats.errors.map(error => console.log(error.red));
  }

  if (jsonStats.hasWarnings) {
    console.log('Webpack generated the following warnings: '.bold.yellow);
    jsonStats.warnings.map(warning => console.log(warning.yellow));
  }

  console.log(`Webpack stats: ${stats}`);

  source.forEach(copyStaticFiles);

  console.log('Your app has been compiled in production mode and written to /public.'.green);

  return 0;
});

我甚至不知道从哪里开始,也找不到有关此类错误的任何文档。

如果需要,我可以提供更多信息。 感谢您阅读我的文章

2个回答

好的,所以我没有带有 HardwareKeyboardArrowDown 的对象,因此我查看了我的依赖项,发现它来自 matérial-ui 依赖项。

我在我的 package.json 中强制使用版本 17.4,并且成功了!

Hydeo
2017-05-14

该消息为您提供了返回无效对象的函数(组件)的名称。 HardwareKeyboardArrowDown
因此,您应该查看其 render 函数的 return ,并确保返回有效的 React 元素(或 null)
这意味着没有 undefinedarray 等。

Sagiv b.g
2017-05-12