您不必使用nodemon,您可以使用webpack's watch feature。
下面是一个示例脚本,让我们把它backend-dev.js
:
const path = require('path');
const webpack = require('webpack');
const spawn = require('child_process').spawn;
const compiler = webpack({
// add your webpack configuration here
});
const watchConfig = {
// compiler watch configuration
// see https://webpack.js.org/configuration/watch/
aggregateTimeout: 300,
poll: 1000
};
let serverControl;
compiler.watch(watchConfig, (err, stats) => {
if (err) {
console.error(err.stack || err);
if (err.details) {
console.error(err.details);
}
return;
}
const info = stats.toJson();
if (stats.hasErrors()) {
info.errors.forEach(message => console.log(message));
return;
}
if (stats.hasWarnings()) {
info.warnings.forEach(message => console.log(message));
}
if (serverControl) {
serverControl.kill();
}
// change app.js to the relative path to the bundle created by webpack, if necessary
serverControl = spawn('node', [path.resolve(__dirname, 'app.js')]);
serverControl.stdout.on('data', data => console.log(data.toString()));
serverControl.stderr.on('data', data => console.error(data.toString()));
});
当您在您的服务器代码的更改,您就可以开始在命令行上此脚本
node backend-dev.js
,的WebPack将重新编译并重新启动服务器。
您通常不会将Webpack用于服务器部件,它更有针对性地捆绑客户端资源,如浏览器JS,CSS,图像等。有什么特别的原因可以说明您希望为服务器使用Webpack ? – damd
对服务器使用webpack有很好的理由,例如,如果你在服务器端编译React组件 –
@PatrickHund:你说得对,但是因为OP是新的工具,所以我只是想让当然,他们知道他们为什么使用它:) – damd