可以在服务器端使用NGINX和Webpack-Hot-Middleware吗?

16

我正在为客户开展一个项目,需要使用webpack的热模块替换功能。我在NGINX后面使用express (node) 应用程序。我使用了许多JavaScript框架来设计应用程序,其中React是其中之一。

我将使用HMR功能。

我有一个像这样的webpack.config.js文件:

var webpack = require('webpack');
var ExtractTextPlugin = require("extract-text-webpack-plugin");
var merge = require('webpack-merge');
var validate = require('webpack-validator');
var CleanWebpackPlugin = require('clean-webpack-plugin');
var styleLintPlugin = require('stylelint-webpack-plugin');

//breaking up into smaller modules
//commons module
//first
var start = {        
 context : __dirname ,

 //entry point defination
 entry : { 
    app : ['./require.js','webpack-hot-middleware/client?https:127.0.0.1:8195'], 
    vendor : ['angular','angular-animate','angular-messages','angular-aria','angular-route','angular-material','react','react-dom',''webpack-hot-middleware/client?https:127.0.0.1:8195'']

 },
 //output defination
 output : {
    path : './public/dist',
  publicPath: 'https://127.0.0.1:8195/public/dist/',
    filename : 'app.bundle.js'
 },
 module: { preLoaders: [
      {
        test: /\.(js|jsx)$/,
         exclude: /(node_modules|bower_components)/,
        loaders: ['eslint']
      }    
    ],
    loaders: [
            {test: /\.js$/, loader: 'ng-annotate!babel?presets[]=es2015!jshint', exclude: /node_modules/},
            {
                test: /\.css$/,
                exclude: /(node_modules|bower_components)/,
                loader: ExtractTextPlugin.extract("style-loader", "css")
            },
            {
                test: /\.less$/,
                exclude: /(node_modules|bower_components)/,
                loader: ExtractTextPlugin.extract("style", "css!less")
            },
            {
                test: /\.scss$/,
                exclude: /(node_modules|bower_components)/,
                loader: ExtractTextPlugin.extract("style", "css!sass")
            },
            {
                test: /\.jsx?$/,
                exclude: /(node_modules|bower_components)/,
                loaders: ['react-hot', 'babel'],

            },
            {
                test: /\.woff2$/,
                loader: 'url'
            }

        ]
    },
 plugins: [

    new webpack.optimize.CommonsChunkPlugin(/* chunkName= */"vendor", /* filename= */"vendor.bundle.js"),
    new webpack.DefinePlugin({
     "process.env": {
          NODE_ENV: JSON.stringify("production")
      }
    }),
    new ExtractTextPlugin("styling.css", {allChunks: true}),
    new ExtractTextPlugin("styling.css", {allChunks: true}),
    new ExtractTextPlugin("styling.css", {allChunks: true}),
    //new webpack.optimize.UglifyJsPlugin({
    //compress: {
     //  warnings: false
    // },

 //}),
 //   new webpack.optimize.DedupePlugin(),
  //  new webpack.optimize.OccurrenceOrderPlugin(), 
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ],
  //target: 'web'
};

var config;

// Detect how npm is run and branch based on that
//choose modules
//all modules
switch(process.env.npm_lifecycle_event) {
  case 'build':
    config = merge(start);
    break;
  default:
    config = merge(start);
}

//export config
module.exports = validate(config); 

我的app.js文件包括:

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
//webpack development server integration 
app.use(require("webpack-dev-middleware")(compiler, {
    noInfo: false, stats: { colors: true,
            chunks: true, 
            'errors-only': true }, headers: { "X-Custom-Header": "yes" },  publicPath: webpackConfig.output.publicPath

}));
app.use(require("webpack-hot-middleware")(compiler, {
   log: console.log
}));

我的 NGINX 文件包括

location / {
...
proxy_pass  https://127.0.0.1:8195; 
...
...
} 
当我打开https://127.0.0.1:8195时,文件被创建和提供。Express监听8195端口。 但是当我打开https://domain-name.com时,文件没有被提供,但NGINX没有显示502错误。

这似乎是一个NGINX配置/DNS问题,因为您可以通过127.0.0.1访问您的文件,但不能通过域名访问。 - detay
10
为什么你在服务器上使用 webpack?Webpack 是用于开发的。 - Cisco
我想强调Francisco Mateo的评论,为什么你需要在nginx服务器上使用这个? - George
2
@FranciscoMateo 和 George,一些人会使用 nginx 在远程机器上进行开发。nginx 只是一个服务器,并不意味着它必须用于生产环境。Express 也是一个服务器,但人们经常在开发中使用它。 - VCavallo
@VCavallo 是的,我知道这一点,但通常使用诸如 Citrix 远程连接到桌面来完成。nginx是一个网络服务器,webpack是一个打包工具。无论是开发还是生产环境,在 nginx 服务器上都没有使用 webpack 的任何理由。 - Cisco
显示剩余4条评论
2个回答

4

的确如此。需要进行一些配置才能适应Websockets HMR使用。

以下是您可以使用的示例配置。

nginx:

  location /my-path {
    proxy_set_header Host $http_host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_http_version 1.1;
    proxy_set_header Connection $http_connection;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Sec-WebSocket-Extensions $http_sec_websocket_extensions;
    proxy_set_header Sec-WebSocket-Key $http_sec_websocket_key;
    proxy_set_header Sec-WebSocket-Version $http_sec_websocket_version;
    proxy_cache_bypass $http_upgrade;
    proxy_read_timeout 900;
    client_max_body_size 0;
    proxy_buffering off;
    add_header X-Accel-Buffering no;
    proxy_pass http://my-internal-server;
  }

webpack.config.js:

const webpack = require('webpack')

module.exports = {
  mode: mode,
  entry: {
    main: [
      `webpack-hot-middleware/client?path=__webpack__/__webpack_hmr&timeout=20000`,
      'app/main.js')
    ]
  },
  devServer: {
    hot: true
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin()
  ]
}

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接