如何在webpack dev服务器中启用root代理?

时间:2018-05-13 22:06:36

标签: webpack

我有一个服务器在localhost:5474上运行,我有一个webpack dev服务器。我希望webpack dev服务器代理localhost:5474

如果我提供URL的额外部分,我的代理工作正常,但我不想这样做。

按照here的说明,它会说

  

请注意,默认情况下,对root的请求不会被代理。启用root   代理时,devServer.index选项应指定为falsy   值:

devServer: {
  index: '', // specify to enable root proxying
  host: '...',
  contentBase: '...',
  proxy: {
    context: () => true,
    target: 'http://localhost:1234'
  }
}

我不确定这些点是什么意思。这是否意味着我在那里放点或这是否意味着我应该为hostcontentBase提供自己的值?

到目前为止,这是我的webpack配置:

const path = require("path");
const webpack = require("webpack");

module.exports = {
  entry: ["./src/js/app.js"],
  output: {
    path: path.resolve(__dirname, "dist"),
    filename: "js/app.js"
  },
  devServer: {
    port:3037,


    open: true,
    hot: true,

    index: '', //needed to enable root proxying

    proxy: {
      //root proxying (doesn't work yet)
      context: () => true,
      target: 'http://localhost:5474',

      //proxying with a URL value (works)
      /*
      "/api": {
        target: "http://localhost:5474",
        pathRewrite: {"^/api" : ""}
      }*/
    },
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader"
        }
      }
    ]
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin()
  ],
  mode:'development'
};

但是当我运行命令时,它会打开http://localhost:3037/并显示列表目录。

如何使用webpack-dev-server将localhost:3037代理到localhost:5474

2 个答案:

答案 0 :(得分:2)

尝试使用类似这样的东西。请注意publicPath: '/public/',这是您的bundle.js能够即时重新加载的地方。

devServer: {
    index: '', //needed to enable root proxying
    port: 10001,
    publicPath: '/public/',
    proxy: {
        context: () => true,
        '/': 'http://localhost:10000'
    }
},

答案 1 :(得分:1)

在最新版本的webpack中是可能的。如文档所述,https://webpack.js.org/configuration/dev-server/

请注意,默认情况下不会代理对root的请求。要启用根代理,应将devServer.index选项指定为假值

该页面提供了一个空字符串的示例,该字符串可以在我的设置中使用。