Request: Webpack

Created on 6 Apr 2015  ·  41Comments  ·  Source: request/request

I'm attempting to load request using Webpack and am seeing this error:

screen shot 2015-04-06 at 13 04 59

I have seen that this is supposed to work in the browser using browserify and was curious what I'm doing wrong. Maybe browserify processes the dependencies differently from webpack which is causing this issue. Any ideas?

Most helpful comment

Same issue here.

The solution: install json-loader so that webpack can handle *.json files. Then add that loader and a new node object to your webpack.config.js like so:

$ npm install --save-dev json-loader

webpack.config.js

var path = require('path');

module.exports = {
  entry: 'index',
  output: {
    path: path.join(__dirname, 'scripts'),
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      { test: /\.json$/, loader: 'json-loader' }
    ]
  },
  resolve: {
    extensions: ['', '.webpack.js', '.web.js', '.js']
  },
  node: {
    console: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty'
  }
};

All 41 comments

+1, also seeing this

Output:

ERROR in ./~/request/lib/har.js
Module not found: Error: Cannot resolve module 'fs' in /absolute/path/to/project/node_modules/request/lib
 @ ./~/request/lib/har.js 3:9-22

ERROR in ./~/request/~/tunnel-agent/index.js
Module not found: Error: Cannot resolve module 'net' in /absolute/path/to/project/node_modules/request/node_modules/tunnel-agent
 @ ./~/request/~/tunnel-agent/index.js 3:10-24

ERROR in ./~/request/~/tunnel-agent/index.js
Module not found: Error: Cannot resolve module 'tls' in /absolute/path/to/project/node_modules/request/node_modules/tunnel-agent
 @ ./~/request/~/tunnel-agent/index.js 4:10-24

ERROR in ./~/request/~/forever-agent/index.js
Module not found: Error: Cannot resolve module 'net' in /absolute/path/to/project/node_modules/request/node_modules/forever-agent
 @ ./~/request/~/forever-agent/index.js 6:10-24

ERROR in ./~/request/~/forever-agent/index.js
Module not found: Error: Cannot resolve module 'tls' in /absolute/path/to/project/node_modules/request/node_modules/forever-agent
 @ ./~/request/~/forever-agent/index.js 7:10-24

ERROR in ./~/request/~/tough-cookie/lib/cookie.js
Module not found: Error: Cannot resolve module 'net' in /absolute/path/to/project/node_modules/request/node_modules/tough-cookie/lib
 @ ./~/request/~/tough-cookie/lib/cookie.js 23:10-24

ERROR in ./~/request/~/form-data/lib/form_data.js
Module not found: Error: Cannot resolve module 'fs' in /absolute/path/to/project/node_modules/request/node_modules/form-data/lib
 @ ./~/request/~/form-data/lib/form_data.js 7:9-22

ERROR in ./~/request/~/har-validator/~/is-my-json-valid/~/jsonpointer/jsonpointer.js
Module not found: Error: Cannot resolve module 'console' in /absolute/path/to/project/node_modules/request/node_modules/har-validator/node_modules/is-my-json-valid/node_modules/jsonpointer
 @ ./~/request/~/har-validator/~/is-my-json-valid/~/jsonpointer/jsonpointer.js 1:14-32

I figured it out. The problem is that Webpack requires some extra config unlike browserify due to it's more barebones nature. See my example branch and diff for how I got the tests to run successfully.

https://github.com/request/request/compare/master...pho3nixf1re:webpack-tests

My plan is to turn that into it's own karma test and submit a PR so others can use it as an example. Also, it may uncover future issues as development progresses.

Yeah, found the same, thanks. For anyone else that stumbles across this, the relevant webpack docs are here: http://webpack.github.io/docs/configuration.html#node

@jaredmcdonald thanks a lot :)

@pho3nixf1re it would be great if you submit a PR about testing request with webpack (additional test, not in place of the browserify one) :+1:

Yes! I intend to. I only replaced it in my branch as a quick proof of concept. I'll get on that this weekend.

Adding the json webpack loader unfortunately did not fix this for me.

Same issue here.

The solution: install json-loader so that webpack can handle *.json files. Then add that loader and a new node object to your webpack.config.js like so:

$ npm install --save-dev json-loader

webpack.config.js

var path = require('path');

module.exports = {
  entry: 'index',
  output: {
    path: path.join(__dirname, 'scripts'),
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      { test: /\.json$/, loader: 'json-loader' }
    ]
  },
  resolve: {
    extensions: ['', '.webpack.js', '.web.js', '.js']
  },
  node: {
    console: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty'
  }
};

Adding the node: { ... } object avoids the error, but then I can't use console in the browser. Is there a way around this?

I just figured it out:

node: {
    console: true
}

This was a huge help for me. Thanks to all above.

Thanks all, bumped into this myself.

any luck?

I'm using webpack & request and got the error you all got here.
Tried the solution with the json-loader & node element and still getting the errors...

Hi. I need help. I want to combine node js mysql into my react app. But i got error message cannot resolve module 'net' when i run the webpack.
Please see codes below:

import React from 'react'
import ReactDOM from 'react-dom'
import mysql from 'mysql'

export default class Server extends React.Component{
render(){
return(
<div>
<div>Success Inserting New Data</div>
<div>Company Name: {this.props.name}</div>
<div>Email: {this.props.email}</div>
</div>
);
}
}

var company_data = {
name: 'Company Name Sample',
email: '[email protected]'
};

let connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'earnmoredoless'
});

connection.connect();

let sql = connection.query('insert into account set ?', data, function(err, res){

`//success`
`if(!err){`

    `ReactDOM.render(`
        `<Server data={company_data} />,`
        `document.querySelector('#app')`
    `);`

`}else{`

    `console.log('Failed inserting new data.');`
`}`

});

+1
this saved me

+1
Saved!

+1 I had problems with dotenv myself. The solution above solved my issue. Thanks!

Adding node { fs: 'empty' } resolved the cannot resolve module 'fs' issue for me, but now my console has an error TypeError: fs.readFileSync is not a function. I'm running into this issue while trying to use dotev and webpack with es6 babel transpiler. Importing webpack as import 'dotenv/config'; as described in https://github.com/motdotla/dotenv/issues/114

While the node {} solution above helped my webpack.config.js it broke my karma.conf.js which depends on it, with the following error:

ReferenceError: Strict mode forbids implicit creation of global property '_crypto'

Anyone solved this to work with dotenv?

I'm having this issue while trying to use node-soap, which depends on request in a React app that uses webpack. I've tried modifying my webpack config to contain;

node: {
    console: true,
    fs: 'empty',
    net: 'empty',
    tls: 'empty'
  }

As suggested above, but that didn't resolve the issue for me. I'm still seeing these errors;
screen shot 2016-08-14 at 5 45 02 pm

Others are seeing the same issues;
https://gitter.im/vpulim/node-soap/archives/2016/04/13
https://gitter.im/vpulim/node-soap/archives/2016/01/11

And as far as I'm aware no one has a solution yet. I'm not super familiar with webpack, but if no one else has a solution yet, I may try to shave that yak this weekend if I have the time so I can debug this further.

@kevhuang @sailingthoms @MrOutis or @gaearon Have any of you discovered a solution for this yet? Or do you have any ideas about what else needs to be done to get node-soap/request working with React? (Preferably with create-react-app without having to eject).

@screendriver Where did you get the information about the _node object_? I'm don't see it in the documentation.

@richburdon, @lucasbento Do have an example for help you?

@garethderioth sorry I can't remember. It's been too long.

By the way: meanwhile I am using the HTML5 fetch API and this polyfill for my AJAX requests.

@garethderioth
@jaredmcdonald said it above in https://github.com/request/request/issues/1529#issuecomment-90347445

Yeah, found the same, thanks. For anyone else that stumbles across this, the relevant webpack docs are here: http://webpack.github.io/docs/configuration.html#node

By the way: meanwhile I am using the HTML5 fetch API and this polyfill for my AJAX requests.

Create React App users: please note that CRA already includes a window.fetch polyfill so you can safely use it instead of request if it satisfies your use case.

@screendriver @josiahsprague Instead of this:

node: {
    console: true,
    fs: 'empty',
    net: 'empty',
    tls: 'empty'
}

I wrote:

target: 'node',

It solved all my issues.

Edit: You can read more about it here: https://webpack.github.io/docs/configuration.html#target

@gaearon What if the dependency is required by some third library? (Eg. node-glob in my case requiring fs, instead of request?)
Raising an issue at create-react-app's repository, as I should have from the beggining :/

My screenshot of errors posted above is irrelevant, which is probably obvious to anyone who read those errors. 😂 Anyway, it seems that both of the solutions in @pedzed's comment would work for me. Another potential solution is using target: 'node-webkit or another similar option depending on your situation..

In my case, I just switched from node-soap to browser-soap, but that won't work for everyone.

I had a different issue that's similar to this, but ended up being socketio/socket.io-client/issues/933 for anyone who may experience it

+1
Thanks!

I made a small change using what @screendriver & @kilometers provided (thanks!).

Webpack complained if there was an empty extension, however, I don't think this would be required for most.

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

module.exports = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/dist/',
filename: 'build.js'
},
module: {
rules: [
{
test: /.json$/,
loader: 'json-loader'
}
]
},
resolve: {
/extensions: ['.webpack.js', '.web.js', '.js']/
}
node: {
console: true,
fs: 'empty',
net: 'empty',
tls: 'empty'
}
}
````

Best easy solution without affecting bundled code:

require

For peeps who have trouble with storybook and don't want to replace storybook's original webpack config, you can extend it by creating .storybook/webpack.config.js and add:

// Load the default config generator.
const genDefaultConfig = require('@kadira/storybook/dist/server/config/defaults/webpack.config.js');

module.exports = function (config, env) {
    const newConfig = genDefaultConfig(config, env);

    // Extend to resolve fs issues
    newConfig.node = {
        fs: 'empty'
    };

    return newConfig;
};
  node: {
    console: true,
    fs: 'empty',
    net: 'empty',
    tls: 'empty'
  }

Using this above code error has been solved but

fs.writeFile('/home/react-hello-world/test.txt', 'aaa', function(err) { alert(err); });

fs.writeFile is not working please give any solution.

@chandrasekarb try set fs to true instead of 'empty'

target: 'node', worked for me :department_store:

I ran into this issue and it was because I was running a dual client/server config for server side rendering. The server-side rendering config was marked as target: 'node', while the client config didn't have one specified. I added target: 'web' to the client config and the error went away.

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

Request is now in maintenance mode and wont be merging any new features or addressing this bug. Please see #3142 for more information.

I had the same issue trying to use jQuery with Nuxt (or Node), the problem was I was importing jQuery and Bootstrap and added jsdom to solve it but did not work. I solved it importing libraries directly in head section of nuxt.config.js, another way is to set client mode in nuxt config plugins, I hope it help someone.

Was this page helpful?
0 / 5 - 0 ratings