Webpack ReferenceError:未定义require(ReactJS)

时间:2018-10-14 21:51:20

标签: javascript reactjs webpack redux react-redux

我知道在浏览器中而不是在节点中调用require()函数时会发生此错误。但是,我似乎无法理解要解决此问题到底需要做什么。任何帮助将不胜感激。您可以转到以下代码库了解整个代码库https://github.com/thegreekjester/React_SSR

运行和重现该问题的步骤:

  • npm安装
  • npm run dev
  • 在浏览器中打开localhost:3000
  • 您将在控制台中看到错误

Webpack.client.js

const path = require('path');
const webpackNodeExternals = require('webpack-node-externals');

module.exports = {

  // production || development
  mode: 'development',

  // Inform webpack that we're building a bundle
  // for nodeJS, rather then for the browser
  target: 'node',

  // Tell webpack the root file of our
  // server application
  entry: './src/client.js',

  // Tell webpack where to put the output file
  // that is generated
  output: {
    filename: 'client_bundle.js',
    path: path.resolve(__dirname, 'build/public'),
    publicPath: '/build/public'
  },
  module: {
    rules: [
      {
        test: /\.js?$/,
        loader: 'babel-loader',
        exclude: '/node_modules/',
        options: {
          presets: [
            'react', 'stage-0', ['env', {
              target: 'web'
            }]
          ]
        }
      }
    ]
  }
};

Webpack.server.js

const path = require('path');
const webpackNodeExternals = require('webpack-node-externals');

module.exports = {

  // production || development
  mode: 'development',

  // Inform webpack that we're building a bundle
  // for nodeJS, rather then for the browser
  target: 'node',

  // Tell webpack the root file of our
  // server application
  entry: './server.js',

  // Tell webpack where to put the output file
  // that is generated
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'build'),
    publicPath: '/build'
  },

  module: {
    rules: [
      {
        test: /\.js?$/,
        loader: 'babel-loader',
        exclude: '/node_modules/',
        options: {
          presets: [
            'react', 'stage-0', ['env', {
              target: { browsers: ['last 2 versions']}
            }]
          ]
        }
      }
    ]
  },

  // Tell webpack not to bundle any libraries that exist in the 'node_modules' folder
  // into the server bundle
  externals: [webpackNodeExternals()]

};

1 个答案:

答案 0 :(得分:0)

在您的webpack.client.js中,请删除密钥target: 'node',因为客户端(浏览器)的Webpack捆绑了。

在您的webpack.server.js中,将密钥libraryTarget: 'commonjs2'添加到output。我看起来像这样:

output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'build'),
    publicPath: '/build',
    libraryTarget: 'commonjs2',
},