簡體   English   中英

Webpack ReferenceError: require 未定義 (ReactJS)

[英]Webpack ReferenceError: require is not defined (ReactJS)

我了解當在瀏覽器中調用require()函數而不是在節點內調用時會發生此錯誤。 但是,我似乎無法理解我到底需要做什么來解決這個問題。 任何幫助將不勝感激。 您可以轉到以下存儲庫獲取整個代碼庫https://github.com/thegreekjester/React_SSR

運行和重現問題的步驟:

  • 安裝
  • npm 運行開發
  • 在瀏覽器中打開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()]

};

在您的webpack.client.js ,請刪除關鍵target: 'node' ,因為 webpack 捆綁客戶端(瀏覽器)。

在你的webpack.server.js ,請添加一個 key libraryTarget: 'commonjs2'output 它看起來像這樣:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM