webpack-dev-server 动态端口

webpack-dev-server dynamic port

是否可以为 webpack-dev-server 找到未使用的端口? 我当前的配置看起来像:

devServer: {
    historyApiFallback: true,
    inline: true,
    host: '0.0.0.0',
    port: 3000,
    contentBase: helpers.root('public'),
    stats: 'minimal'
}

当省略 port 时,webpack-dev-server 使用以 8000 开头的第一个可用端口,请参阅 the PR。需要 webpack-dev-server⩾2.2.

对于早期版本,the port 0 trick could work. See here了解详情。

如果无法省略 port,您可以使用 portfinder-sync 自动 select 下一个可用端口:

const portFinderSync = require('portfinder-sync')

devServer: {
    historyApiFallback: true,
    inline: true,
    host: '0.0.0.0',
    port: portFinderSync.getPort(3000),
    contentBase: helpers.root('public'),
    stats: 'minimal'
}

在我的例子中,我不能省略 port 因为我需要它在我的 devServer 配置中设置 public 属性:

const portFinderSync = require('portfinder-sync')
const port = portFinderSync.getPort(8080)

devServer: {
  contentBase: path.join(__dirname, 'dist'),
  host: '0.0.0.0',
  open: true,
  port: port,
  public: `${ipaddress}:${port}`,
},