Webpack / Node.js Http模块:http.createServer不是一个函数

时间:2017-05-11 12:29:33

标签: javascript node.js webpack

在尝试使用webpack的第一步时,我偶然发现了这个错误。

为了在最基本的级别重现效果,我设置了这样的微文件夹:

节点试验-2

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

具有以下内容:

的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);

现在,如果我只是node main.js,一切都按预期工作。

相反,如果我npm start,从而提示webpack捆绑bundle.js中所需的所有内容然后再运行它,运行时会出现错误http.createServer is not a function错误

进一步检查表明该函数似乎未在bundle.js文件中声明。

我在这里缺少什么?这个webpack实际上是不是意味着什么?

更多,也许毫无意义,信息:

  • 在Windows 10上运行
  • 使用节点版本6.9和7.10
  • 进行测试
  • 在撰写本文时使用webpack和webpack @ beta进行测试

1 个答案:

答案 0 :(得分:9)

默认情况下,Webpack以浏览器环境为目标,http.createServer()没有多大意义。

您可以通过在Webpack配置中添加以下内容来更改目标:

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

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