Rivaler
Rivaler

Reputation: 63

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

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:

Upvotes: 4

Views: 4402

Answers (1)

robertklep
robertklep

Reputation: 203359

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/

Upvotes: 15

Related Questions