2017-02-12 65 views
0

我在使用webpack構建express.js應用程序時遇到了問題。我懷疑我沒有正確處理node.js核心模塊'http'。在webpack build中正確使用節點核心模塊

更具體:我的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; 

唯一的文件在我應用文件夾is 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

嘗試添加var http = require('http');在index.js – owaishanif786

+0

@ owaishanif786我無法直接修改index.js,因爲它是從構建的webpack中得到的。試圖將它添加到index.jsx,但我仍然得到相同的錯誤。 – user1993047

回答

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導入。好吧,這聽起來有點模糊......無論如何,我遇到了其他運行時錯誤...

相關問題