Webpack 获取网页包配置中的网页包开发服务器实例端口

Webpack 获取网页包配置中的网页包开发服务器实例端口,webpack,webpack-dev-server,webpack-2,Webpack,Webpack Dev Server,Webpack 2,当从命令行/NPM脚本运行webpack dev server时,如何在webpack.config.js文件中获取webpack dev server实例的端口号?我不能只使用devServer对象中定义的端口号,因为如果发生端口冲突(同时为另一个项目提供服务),服务器将增加该端口号。谢谢 这并没有达到我最初想要的效果:具体来说,它不是从命令行调用webpack dev server,也不是在webpack config文件中提供端口,但就我而言,这是一种可以接受的解决方法 使用to webp

当从命令行/NPM脚本运行webpack dev server时,如何在webpack.config.js文件中获取webpack dev server实例的端口号?我不能只使用
devServer
对象中定义的端口号,因为如果发生端口冲突(同时为另一个项目提供服务),服务器将增加该端口号。谢谢

这并没有达到我最初想要的效果:具体来说,它不是从命令行调用webpack dev server,也不是在webpack config文件中提供端口,但就我而言,这是一种可以接受的解决方法

使用to webpack dev server,您可以使用API启动服务器,通过为port参数传入
0
请求随机端口,并访问server.js文件中的端口号:

'use strict';

const Webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const webpackConfig = require('./webpack.config');

const compiler = Webpack(webpackConfig);
const server = new WebpackDevServer(compiler, {
  stats: {
    colors: true
  }
});

server.listen(0, '127.0.0.1', () => {
  const port = server.listeningApp.address().port;

  // use port here
});

这并不是我最初想要的:具体来说,它不是从命令行调用webpack dev server,也不是在webpack配置文件中提供端口,但就我而言,这是一个可以接受的解决方法

使用to webpack dev server,您可以使用API启动服务器,通过为port参数传入
0
请求随机端口,并访问server.js文件中的端口号:

'use strict';

const Webpack = require('webpack');
const WebpackDevServer = require('webpack-dev-server');
const webpackConfig = require('./webpack.config');

const compiler = Webpack(webpackConfig);
const server = new WebpackDevServer(compiler, {
  stats: {
    colors: true
  }
});

server.listen(0, '127.0.0.1', () => {
  const port = server.listeningApp.address().port;

  // use port here
});

如果在
devServer
中省略
端口
,webpack将自动为您选择下一个可用端口。但是,如果出于某种原因不能忽略端口,请查看一下,以便在webpack.config.js中使用它来设置端口值
const-port=portFinderSync.getPort(8080)
不幸的是,这不再适用于webpack dev server版本3+Oh,但事实证明,您仍然可以使用
onListening
选项访问它,例如
onListening:server=>{const{port}=server.listeningApp.address();…}
如果您在
devServer
中省略
端口
,webpack将自动为您选择下一个可用端口。但是,如果出于某种原因不能忽略端口,请查看一下,以便在webpack.config.js中使用它来设置端口值
const-port=portFinderSync.getPort(8080)
不幸的是,这不再适用于webpack dev server版本3+Oh,但事实证明,您仍然可以使用
onListening
选项访问它,例如
onListening:server=>{const{port}=server.listeningApp.address();…}