使用webpack-dev-server

时间:2015-12-19 07:38:19

标签: node.js webpack webpack-dev-server

我使用Express,React和Webpack构建了一个应用程序。我使用webpack-dev-server和react-hot-loader来实现生活。

Express服务器位于端口3000上,而webpack-dev服务器服务器位于localhost:8080上。

现在我想从局域网中的另一个客户端访问该应用程序。我可以访问development machine IP:3000,但无法访问localhost:8080

我的webpack.config.dev.js文件是:

var webpack = require('webpack');

module.exports = {
    devtool: 'inline-source-map',
    entry: [
        'webpack-dev-server/client?http://localhost:8080',
        'webpack/hot/only-dev-server',
        './src/client/entry',
    ],
    output: {
        path: __dirname + '/public/js',
        filename: 'app.js',
        publicPath: 'http://localhost:8080/public/js',
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoErrorsPlugin(),
        new webpack.DefinePlugin({
            "process.env": {
                BROWSER: JSON.stringify(true)
            }
        })
    ],
    resolve: {
        extensions: ['', '.js', '.jsx', '.css']
    },
    module: {
        loaders: [{
            test: /\.jsx?$/,
            loader: 'react-hot',
            exclude: /node_modules/
        }, {
            test: /\.jsx?$/,
            loader: 'babel-loader',
            query: {
                presets: ['react', 'es2015'],
                compact: false
            },
            exclude: /node_modules/
        }, {
            test: /\.css$/,
            loader: 'style-loader!css-loader',
            exclude: /node_modules/
        }, ]
    }
}

,HTML是:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
  <link rel="stylesheet" href="public/css/bootstrap.min.css" media="screen" title="no title" charset="utf-8">
</head>
<body>
  <div id="app">{{ content|safe }}</div>
  <script src="http://localhost:8080/public/js/app.js"></script>
</body>
</html>

webpack-dev-server是

import WebpackDevServer from "webpack-dev-server";
import webpack from "webpack";
import config from "../../webpack.config.dev";

var server = new WebpackDevServer(webpack(config), {
  // webpack-dev-server options
  publicPath: config.output.publicPath,
  hot: true,
  stats: { colors: true },
  headers: { "Access-Control-Allow-Origin": "*" }
});

server.listen(8080, "localhost", function() {});

我希望我可以在我的本地开发机器上保持实时重装,而其他计算机或手机可以通过development machine IP:3000

访问服务器和静态文件

我对webpack不熟悉。我只是按照一些教程来构建开发环境。

我该如何更改配置?

1 个答案:

答案 0 :(得分:0)

如果您想接受来自localhost以外的其他计算机的连接,则需要在hostname电话中配置server.listen参数。在您的情况下,您只允许"localhost"上的连接:

server.listen(8080, "localhost", function() {});

例如,要接受任何地址上的连接,只需删除该参数:

server.listen(8080, function() {});

查看server.listen了解详情。