我在尝试使用 webpack 的第一步时偶然发现了这个错误。
只是为了在最基本的层面上重现效果,我这样设置了这个微型文件夹:
Node 测试 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 上运行
- 已使用 Node 版本 6.9 和 7.10 进行测试
- 在撰写本文时使用 webpack 和 webpack@beta 进行了测试
最佳答案
默认情况下,Webpack 以浏览器环境为目标,http.createServer()
对此没有多大意义。
您可以通过将以下内容添加到您的 Webpack 配置来更改目标:
entry : './main.js',
target : 'node',
...
关于javascript - Webpack/Node.js Http 模块 : http. createServer 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43915463/