我尝试将webpack用于使用socket.io的节点服务器。
我有一个简单的服务器:
var server = require('http').createServer();
var io = require('socket.io').listen(server);
io.on('connection', function(client) {
console.log('new client');
client.on('hello', function(data) {
console.log('msg: ', data);
});
client.on('disconnect', function(){
console.log('client disconnect');
});
});
server.listen(3000);
我的webpack.config.js
var config = {
target: "node",
entry: {
server: ["server.js"]
},
module: {
loaders: [
{
test: /\.(txt|json|osgjs|osgt|bin)$/,
loader: "file?name=[path][name].[ext]"
}
],
noParse: ["ws"]
}
externals: ["ws"],
output: {
path: __dirname,
filename: "[name].js"
}
}
module.exports = config;
当我“编译”时,我没有错误,只是一个警告:
> NODE_ENV=development BUILD_TARGET=server webpack --display-error-details
Hash: a692e23215bcd6caa05a
Version: webpack 1.13.2
Time: 672ms
Asset Size Chunks Chunk Names
_/node_modules/mime-db/db.json 145 kB [emitted]
_/node_modules/socket.io-client/package.json 4.29 kB [emitted]
server.js 572 kB 0 [emitted] server
[0] multi server 28 bytes {0} [built]
[1] ./server.js 346 bytes {0} [built]
+ 88 hidden modules
WARNING in ../~/engine.io/lib/server.js
Critical dependencies:
74:43-65 the request of a dependency is an expression
@ ../~/engine.io/lib/server.js 74:43-65
当我尝试启动服务器时:
fs.js:977
return binding.fstat(fd);
^
Error: EBADF: bad file descriptor, fstat
at Error (native)
at Object.fs.fstatSync (fs.js:977:18)
at tryStatSync (fs.js:462:13)
at fs.readFileSync (fs.js:510:12)
at Object.<anonymous> (/Users/alexis/Documents/server.js:109:21)
at __webpack_require__ (/Users/alexis/Documents/server.js:21:30)
at Object.<anonymous> (/Users/alexis/Documents/server.js:56:34)
at __webpack_require__ (/Users/alexis/Documents/server.js:21:30)
at Object.<anonymous> (/Users/alexis/Documents/server.js:48:19)
at __webpack_require__ (/Users/alexis/Documents/server.js:21:30)
我用:
答案 0 :(得分:5)
警告来自动态需求,例如:
const test = require('scripts/' + scriptName)
忽略它通常是安全的。 Webpack尝试使用上下文模块来处理动态需求,该模块基本上是与动态需求匹配的所有可能模块的表示。 你可以在这里读更多关于它的内容: https://webpack.github.io/docs/context.html
关于错误,如果你不需要将socket.io捆绑在输出包中,你可以将它添加到webpack的外部配置中,webpack会忽略它,但你需要在解决方案中有一个带有socket.io的node_modules文件夹。
所以你的配置将是:
var config = {
target: "node",
entry: {
server: ["server.js"]
},
module: {
loaders: [
{
test: /\.(txt|json|osgjs|osgt|bin)$/,
loader: "file?name=[path][name].[ext]"
}
],
noParse: ["ws"]
}
externals: ["ws", "socket.io"],
output: {
path: __dirname,
filename: "[name].js"
}
}
module.exports = config;
实际上,最好不要在后端应用程序包中包含node_modules依赖项,并且只有一个webpack插件: https://www.npmjs.com/package/webpack-node-externals
如果您想使用该插件,您的配置将是(在安装webpack-node-externals之后):
var nodeExternals = require('webpack-node-externals')
var config = {
target: "node",
entry: {
server: ["server.js"]
},
module: {
loaders: [
{
test: /\.(txt|json|osgjs|osgt|bin)$/,
loader: "file?name=[path][name].[ext]"
}
],
noParse: ["ws"]
}
externals: [nodeExternals()],
output: {
path: __dirname,
filename: "[name].js"
}
}
module.exports = config;