2015-12-22 119 views
2

我正在使用React/Redux项目,并且一直在努力获得superagent的工作。带有Webpack的Superagent:“require is not defined”

在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

回答

1

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

我没有在我的项目中使用superagent,所以我不知道为什么它不需要正确。然而,我也遇到了与其他图书馆行为类似的问题。我最终使用浏览器版本,然后使用webpack将其别名(所以我不必记得每次在我的项目中需要它时都会给出构建版本的完整路径)。

在你的WebPack配置,你可以做这样的事情别名:

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

然后在你的项目,你可以require('superagent')像往常一样的WebPack将解决它在幕后正确。希望这可以帮助!

+0

我尝试了上述解决方案,甚至当我安装包“emitter”和“reducer”时,在superagent的浏览器版本中,我从发射器中得到TypeError。有人与另一个软件包有类似的问题:http://stackoverflow.com/questions/27111552/webpack-causes-syntax-error-in-bundle-output但它似乎没有得到解决。 – hoodsy

相关问题