reactjs - React + Webpack bundle - 如果浏览器中排除了 node_modules 'require is not defined'

标签 reactjs webpack bundle

我正在学习 React,并尝试将其与 Webpack 一起使用,但我面临以下问题:

如果我使用此 webpack 配置,节点模块不会被排除,并且 bundle 过程需要 20 秒,并且 bundle 的大小超过 2MB(请参阅下面的 CLI 输出):

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

module.exports = {
  entry: [
    'bootstrap-loader',
    './src/index.js',
    'style!css!./src/style/style.css'
  ],
  output: {
    path: path.resolve(__dirname + 'build'),
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      { test: /\.jsx?$/,
        loader: 'babel-loader'
      },
      {
        test: /\.scss$/,
        loaders: [
          'style',
          'css?modules&importLoaders=2&localIdentName=[name]__[local]__[hash:base64:5]',
          'postcss',
          'sass',
        ],
      },
      {
        test: /\.woff2?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
        loader: "url?limit=10000"
      },
      {
        test: /\.(ttf|eot|svg)(\?[\s\S]+)?$/,
        loader: 'file'
      },
      // Bootstrap 3
      { test:/bootstrap-sass[\/\\]assets[\/\\]javascripts[\/\\]/, loader: 'imports?jQuery=jquery' },
    ]
  }
}

CLI output 1

... enter image description here

但是,如果我将以下两行添加到我的配置中并使用 nodeExternals,则 bundle 会变小并且运行速度很快,尽管它不起作用,因为在浏览器中我收到错误 'Uncaught ReferenceError: require is not定义':

  ...
  target: 'node', // important in order not to bundle built-in modules like path, fs, etc.
  externals: [nodeExternals()]
  ...

enter image description here

我在这里缺少什么?我想浏览器会抛出这个错误,因为在我排除node_modules之后,客户端不再存在react,但是我认为node_modules不应该被 bundle 。 请在这里找到我的有问题的小项目的存储库: https://github.com/sznrbrt/messageboard-react

解决方案:

两种不同的方法是通过正则表达式/node_modules/为加载程序传递排除或包含选项

...
exclude: /(node_modules|bower_components)/,
...

  ...
  { test: /\.js?$/,
    include: [
      path.resolve(__dirname, './src'),
    ],
    loader: 'babel-loader?cacheDirectory',
  },
  ...

最佳答案

答案是在 module.loaders 内添加 exclude:/node_modules/ 字段。

添加目标:'node'意味着打包此代码以在node.js环境中运行,其中包含节点特定的全局变量,如require。这就是它无法在浏览器中运行的原因。

关于reactjs - React + Webpack bundle - 如果浏览器中排除了 node_modules 'require is not defined',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37760639/

相关文章:

javascript - undefined is not a function (evaluating '_this2.closeDrawer()') react native app 错误

reactjs - 创建react-redux布局 header 组件的更好方法

reactjs - 在 React/Nextjs 中导入文件夹中的多个文件

webpack - 导入*为( Jasmine spyOn)不可写

android - 将对象放入包中

ruby-on-rails - 如何彻底清理 ruby​​ on Rails 项目?

reactjs - 如何在浏览器刷新后保持 React 组件状态

javascript - 用于检测图像已完成加载的“加载”事件监听器在 react 中不起作用

javascript - Webpack 没有加载 css

symfony - Oneup/AclBundle的DoctrineSubscriber中的Doctrine依赖变化导致的错误