Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack/Node.js Http module: http.createServer is not a function

I stumbled upon this error while trying my first steps in webpack usage.

Just to reproduce the effect at a very basic level, I set up this micro folder like this:

node-test-2

  • main.js
  • package.json
  • webpack.config.js

With the following contents:


package.json

{
  "name": "node-test-2",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "webpack && node bundle.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "webpack": "^2.2.0"
  }
}

webpack.config.js

var path = require('path');

module.exports = {
    entry : './main.js',
    output : {
        path : path.resolve(__dirname),
        filename : 'bundle.js'
    }
}

main.js

var http   = require('http');

console.log("Creating Server");
var server = http.createServer(function(req, res){
    console.log('Connection Estabilished!');
    res.write('HELLO!');
    res.end();
});

console.log("Listening on port " + 8000);
server.listen(8000);

Now, if I simply node main.js everything works as intended.

On the contrary, if I npm start, thus prompting webpack to bundle everything that's needed in the bundle.js fle and then running it, the error http.createServer is not a function error shows up when running.

Further checks show that the function seems not declared at all in the bundle.js file.

What am I missing here? Is this something webpack actually isn't meant for?

More, maybe meaningless, informations:

  • Running on Windows 10
  • Tested with node version 6.9 and 7.10
  • Tested with both webpack and webpack@beta at the time of writing
like image 595
Rivaler Avatar asked Dec 07 '22 18:12

Rivaler


1 Answers

By default, Webpack targets browser environments, for which http.createServer() doesn't make much sense.

You can change the target by adding the following to your Webpack configuration:

entry  : './main.js',
target : 'node',
...

https://webpack.js.org/configuration/target/

like image 123
robertklep Avatar answered Dec 10 '22 08:12

robertklep