【问题标题】:Superagent with Webpack: "require is not defined"带有 Webpack 的超级代理:“未定义要求”
【发布时间】:2016-03-28 03:53:26
【问题描述】:

我正在处理一个 React/Redux 项目,并且一直在努力让 superagent 工作。

在超级代理问题中关注问题并向我的 webpack.config 文件添加一些解决方法后,我能够构建我的包而没有错误。不幸的是,我现在在浏览器中遇到错误:

require is not defined

指向线路:module.exports = require("tty");

我相信 tty 是一个核心节点模块。此外,对 tty 的要求来自我对客户端的 require('superagent') 调用。

这是我的 webpack 配置:

var path = require('path')
var webpack = require('webpack')

var config = {
  devtool: 'cheap-module-eval-source-map',
  target: 'node',
  entry: [
    'webpack-hot-middleware/client',
    './client/index'
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'bundle.js',
    publicPath: '/static/'
  },
  plugins: [
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
    new webpack.DefinePlugin(
      {
        'process.env.NODE_ENV': '"development"',
        'global.GENTLY': false
      }
    ),
  ],
  module: {
    loaders: [
      { test: /\.json$/, loaders: ['json'], },
      { test: /\.js$/, exlude: /node_modules/, loaders: ['babel', 'eslint'], },
    ]
  },
  // build breaks on eslint without this workaround
  // https://github.com/MoOx/eslint-loader/issues/23
  eslint: {
    emitWarning: true
  },
  node: {
    __dirname: true,
  }
}

module.exports = config;

有人知道我的问题可能是什么吗?我搜索了 webpack 和 superagent 问题,这似乎是最相关的:https://github.com/facebook/react-native/issues/10

【问题讨论】:

    标签: reactjs webpack redux superagent


    【解决方案1】:

    您可以尝试他们的建议 here -- 我看到您已将他们建议的内容添加到您的 webpack 配置中,但也许可以尝试他们的第一个建议,即使用他们的浏览器版本而不是 require('superagent/lib/client)

    我没有在我的项目中使用 superagent,所以我不确定为什么它不需要正确。但是,我对其他库的行为方式类似时遇到了问题。我最终使用了浏览器版本,然后使用 webpack 为其设置别名(因此我不必记住每次在我的项目中需要它时都提供构建版本的完整路径)。

    在您的 webpack 配置中,您可以通过执行以下操作来别名:

    resolve: {
      alias: {
        'superagent': 'path/to/node_modules/superagent/lib/client'
      }
    }
    

    然后在你的项目中,你可以像往常一样require('superagent'),webpack 会在后台正确解决它。希望这会有所帮助!

    【讨论】:

    • 我尝试了上述解决方案,即使我安装了“emitter”和“reducer”包,我在 superagent 的浏览器版本中也从发射器收到了 TypeError。有人对另一个包有类似的问题:stackoverflow.com/questions/27111552/…,但似乎没有解决。
    【解决方案2】:

    将这个(取自 another answer here)添加到我的 webpack 配置中对我有用:

    plugins.push(new webpack.DefinePlugin({ "global.GENTLY": false }));
    

    【讨论】:

      猜你喜欢
      • 2020-07-14
      • 1970-01-01
      • 2017-11-25
      • 2023-03-10
      • 2019-03-19
      • 2018-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多