我在使用webpack构建express.js应用时遇到问题。我怀疑我没有处理node.js核心模块' http'正确。
更具体一点:我的 package.json 看起来像
{
"name": "basic-express-example",
"version": "1.0.0",
"description": "description here",
"main": "index.js",
"author": "",
"license": "ISC",
"scripts": {
"build": "webpack -d"
},
"dependencies": {
"babel-core": "^6.22.1",
"babel-loader": "^6.2.10",
"babel-preset-es2015": "^6.22.0",
"babel-preset-react": "^6.22.0",
"express": "^4.14.1",
"webpack": "^2.2.1"
}
}
我的 webpack.config.js 看起来像
var webpack = require('webpack');
var path = require('path');
var BUILD_DIR = path.resolve(__dirname, 'build');
var APP_DIR = path.resolve(__dirname, 'app');
var config = {
entry: APP_DIR + '/index.jsx',
output: {
path: BUILD_DIR,
filename: 'index.js'
},
module : {
loaders : [
{
test : /\.jsx?/,
include : APP_DIR,
exclude : [
/node_modules/,
/build/
],
loader : 'babel-loader'
}
]
},
node: {
fs: 'empty',
net: 'empty'
}
};
module.exports = config;
app 文件夹中唯一的文件是 index.jsx :
import express from 'express';
const app = express();
现在,如果我使用npm build
构建应用,然后尝试使用node build/index.js
运行生成的文件,则会出现类型错误
undefined:31
__proto__: http.IncomingMessage.prototype
^
TypeError: Cannot read property 'prototype' of undefined
如何解决此问题,即如何使http模块可用?
提前感谢您的帮助!
答案 0 :(得分:0)
我使用this link通过将以下内容添加到webpack配置来捆绑节点模块来解决它:
var fs = require('fs');
var nodeModules = {};
fs.readdirSync('node_modules')
.filter(function(x) {
return ['.bin'].indexOf(x) === -1;
})
.forEach(function(mod) {
nodeModules[mod] = 'commonjs ' + mod;
});
...
externals: nodeModules,
...
我还尝试通过外部提供http模块并将index.jsx捆绑为commonjs模块来解决它,然后在同一个文件中使用它也提供http导入。好吧,这听起来有点模糊......无论如何,我遇到了其他运行时错误......