如何检测webpack-dev-server是否正在运行?

trnvg8h3  于 2023-05-07  发布在  Webpack
关注(0)|答案(5)|浏览(202)

如何确定webpack.config.js是否通过webpackwebpack-dev-server加载?

pod7payv

pod7payv1#

更新:环境变量为changedWEBPACK_SERVE

webpack开发服务器will now设置了WEBPACK_DEV_SERVER环境变量,允许更健壮的检查方式。

const isDevServer = process.env.WEBPACK_DEV_SERVER;
2w3kk1z5

2w3kk1z52#

或者:
const isDevServer = process.argv[1].indexOf('webpack-dev-server') !== -1;
或:
const isDevServer = process.argv.some(v => v.indexOf('webpack-dev-server') !== -1);
或:
const isDevServer = process.argv.some(v => v.includes('webpack-dev-server'));
我一直在使用后者,效果很好。一种配置FTW!

deyfvvtc

deyfvvtc3#

我发现了一个潜在的解决方案:

var isDevServer = path.basename(require.main.filename) === 'webpack-dev-server.js';

credit

jecbmhm3

jecbmhm34#

或者使用Webpack Environment Variables

// The webpack command line
webpack-dev-server --open --env.devServer

// webpack.config.js
module.exports = env => {
  console.log('isDevServer: ', env.devServer) // true
  ...
}
lvjbypge

lvjbypge5#

通常,webpack-dev-servermode='development'(https://webpack.js.org/configuration/mode/#root)一起运行,而webpackmode=production一起运行。如果是,你可以使用的值:

process.env.NODE_ENV

相关问题