webpack-dev-server端口自动分配

时间:2019-05-06 14:35:50

标签: webpack webpack-dev-server

我想设置我的webpack-dev-server的端口自动分配。 但似乎不起作用。 我该怎么办?

webpack.config.js

const net = require('net');

module.exports = {
 devServer: {
      port: checkPort(5000).then((port) => getPort(port)),
      host:"localhost"
    }
}

function checkPort(port) {
  const server = net.createServer().listen(port, 'localhost');
  return new Promise(resolve => {
    server.on('listening', () => {
      server.close();
      resolve(port);
    });
    server.on('error', err => {
      console.log("err: ", err);
      resolve(getPort(port+1));
    })
  })
}

function getPort(port) {
  console.log("targetPort: ", port);
  return port;
}

如果端口5000繁忙,则使用5001。 但出现错误:

Invalid configuration object. webpack-dev-server has been initialised using a configuration object that does not match the API schema.

我总是无法到达正确的端口。

1 个答案:

答案 0 :(得分:0)

我以这种方式解决了这个问题。 enter image description here

您可以看到webpack的配置类型in here的文档


const net = require('net');
const webpackMerge = require('webpack-merge');
const commonConfig = require('./configs/webpack.common');

let PORT = 5000;
function checkPort(port) {
  PORT = port;
  const server = net.createServer().listen(port, 'localhost');
  server.on('listening', function() {
    server.close();
  });
  server.on('error', err => {
    if (err.code === 'EADDRINUSE') {
      checkPort(port + 1);
    }
  });
}
checkPort(PORT);

module.exports = env => {
  const envConfig = require(`./configs/webpack.${env.env}.js`);
  const isDevEnv = env.env === 'dev';
  let portConfig = {};
  return new Promise(resolve => {
    setTimeout(() => {
      if (isDevEnv) {
        portConfig.devServer = {
          port: PORT
        };
      }
      resolve(webpackMerge.smart(commonConfig, envConfig, portConfig));
    }, 100);
  });
};