在 webpack 构建中正确使用节点核心模块



我在使用 webpack 构建快速.js应用程序时遇到问题。我怀疑我没有正确处理节点.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;

我的应用程序文件夹中的唯一文件是 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 模块可用?

提前感谢您的任何帮助!

我使用此链接解决了它,通过不通过将以下内容添加到 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 导入的同一文件中使用。好吧,这听起来有点模糊...无论如何,我在那里遇到了其他运行时错误......

最新更新