如何将我的后端从当前的webpack dev服务器更改为表达?

时间:2016-05-08 08:32:17

标签: express reactjs webpack backend webpack-dev-server

我一直在阅读一篇描述Reactjs webpack和webpac dev服务器的教程。但现在我必须在我的真实项目中使用express。如何更改服务器,或者我可以使用express添加新服务器,在这种情况下如何管理两个localhost?你可以在下面看到我的webpack.config.js。



var debug = process.env.NODE_ENV !== "production";
var webpack = require('webpack');
var path = require('path');

module.exports = {
  context: path.join(__dirname, "src"),
  devtool: debug ? "inline-sourcemap" : null,
  entry: "./app/main.js",
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        //test: /\.js?$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel-loader',
        query: {
          presets: ['react', 'es2015', 'stage-0'],
          plugins: ['react-html-attrs', 'transform-class-properties', 'transform-decorators-legacy'],
        }
      }
    ]
  },
  output: {
    path: __dirname + "/src/",
    filename: "index.js"
  },
  plugins: debug ? [] : [
    new webpack.optimize.DedupePlugin(),
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false }),
  ],
};




现在我已经通过express构建了一个服务器,它监听3000:



var path = require('path');
var express = require('express');
var bodyParser = require('body-parser');

var app = express();

app.set('port', (process.env.PORT || 3000));

app.use('/', express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.listen(app.get('port'), function() {
  console.log('Server started: http://localhost:' + app.get('port') + '/');
});




我的webpack dev服务器有路径./node_modules/.bin并且它监听8080.问题是我应该在express文件中添加什么来接管webpack dev服务器。或者如果您认为我可以将它们合并,在这种情况下我应该如何操作快递?谢谢!

1 个答案:

答案 0 :(得分:0)

你可以将express与webpack-dev-middleware结合起来

var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config.dev');

var app = express();
var compiler = webpack(config);

app.use(require('webpack-dev-middleware')(compiler, {
  noInfo: true,
  publicPath: config.output.publicPath
}));

app.get('*', function(req, res) {
  res.sendFile(path.join(__dirname, 'index.html'));
});

app.listen(3000, function(err) {
  if (err) {
    console.log(err);
    return;
  }

  console.log('Listening at http://localhost:3000');
});