重启服务器是一回事,刷新浏览器是另一回事。对于服务器观看,我使用 nodemon。 Nodemon 可以查看任何类型的文件何时发生更改。但是 nodemon 无法刷新浏览器页面。为此,我使用浏览器同步。
我都在 gulp 中使用。
因此,package.json 的依赖项使其工作:
"devDependencies": {
"browser-sync": "^2.24.5",
"gulp": "^3.9.1",
"gulp-nodemon": "^2.2.1"
}
在服务器文件中(我的服务器在./bin/www,你的可以在server.js、app.js或其他地方),express server监听3001端口。
var port = normalizePort(process.env.PORT || '3001');
var server = http.createServer(app);
server.listen(port);
接下来是在 gulp 中运行 nodemon 和浏览器同步。
gulpfile.js 的完整内容
var gulp = require('gulp');
var nodemon = require('gulp-nodemon');
var browserSync = require('browser-sync').create();
gulp.task('gulp_nodemon', function() {
nodemon({
script: './bin/www', //this is where my express server is
ext: 'js html css', //nodemon watches *.js, *.html and *.css files
env: { 'NODE_ENV': 'development' }
});
});
gulp.task('sync', function() {
browserSync.init({
port: 3002, //this can be any port, it will show our app
proxy: 'http://localhost:3001/', //this is the port where express server works
ui: { port: 3003 }, //UI, can be any port
reloadDelay: 1000 //Important, otherwise syncing will not work
});
gulp.watch(['./**/*.js', './**/*.html', './**/*.css']).on("change", browserSync.reload);
});
gulp.task('default', ['gulp_nodemon', 'sync']);
当在终端运行 gulp 时,它将开始监视服务器并在任何文件更改时刷新浏览器。
虽然我们在 express 服务器中指定了端口 3001,但我们的应用程序将在端口 3002 上运行,因为我们在 browser-sync 中编写。 3001 将用作代理。