node.js gulp.js livereload 与 express 服务器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23665993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
gulp.js livereload with express server?
提问by Timmerz
I am trying to setup my gulpfile.jsto use livereload on an express server without much luck. I see examples out there but they seem to be related to a static file server.
我正在尝试将我的设置设置gulpfile.js为在快速服务器上使用 livereload,但运气不佳。我看到了一些例子,但它们似乎与静态文件服务器有关。
http://code.tutsplus.com/tutorials/gulp-as-a-development-web-server--cms-20903http://rhumaric.com/2014/01/livereload-magic-gulp-style/
http://code.tutsplus.com/tutorials/gulp-as-a-development-web-server--cms-20903 http://rhumaric.com/2014/01/livereload-magic-gulp-style/
So I have an app.jsfile which does the standard express server with jade files, etc. What I want to do is get it to work with livereload from a gulp.js boot.
所以我有一个app.js文件,它使用 jade 文件等执行标准快速服务器。我想要做的是让它从 gulp.js 启动与 livereload 一起工作。
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
There are lots of plugins like gulp-livereload, connect-livereload, gulp-connect, gulp-watchso how can I get this wired up?
有很多插件,例如gulp-livereload, connect-livereload, gulp-connect,gulp-watch那么我该如何连接呢?
回答by Amit Portnoy
I've added code that
我已经添加了代码
Detects changes in server files and reloads the server via nodemon
Waits for a couple seconds after process reload in order to give the server time to run its initialization code.
Triggers a change in a livereload server
检测服务器文件的变化并通过nodemon重新加载服务器
在进程重新加载后等待几秒钟,以便让服务器有时间运行其初始化代码。
触发 livereload 服务器的更改
note 1: Your build should also include a livereload server and attach livereload scripts to html files before calling the 'serve' task
注意 1:您的构建还应该包括一个 livereload 服务器,并在调用“服务”任务之前将 livereload 脚本附加到 html 文件
note 2: This is an asynchronous task that never ends, do notuse it as a dependency of other tasks
注意2:这是一个永不结束的异步任务,不要将其用作其他任务的依赖项
gulp.task('serve', function (cb) {
nodemon({
script : <server start file>,
watch : <server files>
//...add nodeArgs: ['--debug=5858'] to debug
//..or nodeArgs: ['--debug-brk=5858'] to debug at server start
}).on('start', function () {
setTimeout(function () {
livereload.changed();
}, 2000); // wait for the server to finish loading before restarting the browsers
});
});
回答by Andrei Rosca
Here's my solution:
这是我的解决方案:
//gulpfile.js:
var gulp = require('gulp');
var nodemon = require('gulp-nodemon');
var server = require('gulp-express');
var lr = require('tiny-lr')();
gulp.task('default', function () {
nodemon({
script: 'server.js'
})
.on('restart', function () {
console.log('restarted!')
});
lr.listen(35729);
gulp.watch('server/**/*', function(event) {
var fileName = require('path').relative('3000', event.path);
lr.changed({
body: {
files: [fileName]
}
});
});
});
You also need to include connect-livereload in your express server:
您还需要在您的快速服务器中包含 connect-livereload:
app.use(require('connect-livereload')());
Include it before bodyParser. I have read that this is not needed if you have the chrome live reload extension.
在 bodyParser 之前包含它。我已经读到,如果您有 chrome live reload 扩展,则不需要这样做。
回答by Gimm
gulp-expressis the right thing for you. It runs your express script as a server, with livereload!
gulp-express适合你。它使用 livereload 将您的快速脚本作为服务器运行!
回答by Denis Parchenko
I had the same issue and was not able to find anything related. My solution ends up with the following piece of code in Gulpfile:
我遇到了同样的问题,无法找到任何相关内容。我的解决方案以以下代码结束Gulpfile:
var fork = require('child_process').fork;
var tinyLr = require('tiny-lr');
var async = require('async');
var plugins = require('gulp-load-plugins')({ lazy: false });
var lr = null;
var lrPort = 35729;
var buildDir = 'build';
var serverAppFile = path.join(__dirname, 'build/server/app.js');
// This guy starts and stops nodejs process which runs our Express app
var app = {
start: function(callback) {
process.execArgv.push('--debug');
var instance = app.instance = fork(serverAppFile, {
silent: true
});
app.dataListener = function(data) {
var message = '' + data;
// Assume that server is started when it prints the following to stdout
if (message.indexOf('Express server listening on port') === 0) {
callback();
}
};
instance.stdout.on('data', app.dataListener);
instance.stdout.pipe(process.stdout);
instance.stderr.pipe(process.stderr);
},
stop: function(callback) {
app.instance.stdout.removeListener('data', app.dataListener);
plugins.util.log('Killing Express server with PID', app.instance.pid);
app.instance.kill('SIGTERM');
callback();
}
};
// build-assets task actually processes my client js, less, images, etc and puts them to build dir
// build-server task copies server files (app.js, controllers, views) to build dir
gulp.task('serve', ['build-assets', 'build-server'], function(callback) {
async.series([
app.start,
function(callback) {
lr = tinyLr();
lr.listen(lrPort, callback);
}
], callback);
});
gulp.task('watch', ['serve'], function() {
// Reload page if built files were updated
gulp.watch([
buildDir + '/**/*.handlebars',
buildDir + '/**/*.html',
buildDir + '/**/*.js',
buildDir + '/**/*.css'
], function(event) {
var fileName = path.relative(path.join(__dirname, buildDir), event.path);
plugins.util.log('Detected updated file ' + fileName + ', reloading server and page in browser');
async.series([
// Restart Express server
app.stop,
app.start,
// Send reload notification to browser
function(callback) {
lr.changed({
body: {
files: [fileName]
}
});
callback();
}
]);
});
// Perform build steps on source file modifications
gulp.watch(['app/**/*.js', '!app/**/*.spec.js'], ['build-app-js']);
gulp.watch(['app/**/*.html'], ['build-templates']);
gulp.watch(['app/**/*.less'], ['build-less']);
gulp.watch(['server/**/*.*'], ['build-server']);
});
You'll need to install tiny-lr, async, gulp-utiland gulp-load-pluginspackages for this sample to work.
I guess that I'll create a separate Gulp plugin for it =)
你需要安装tiny-lr,async,gulp-util和gulp-load-plugins包此示例工作。我想我会为它创建一个单独的 Gulp 插件 =)
回答by kwcto
Take a look at gulp-nodemonwhich will restart your server when code changes.
看看gulp-nodemon,它会在代码更改时重新启动您的服务器。
Example:
例子:
gulp.task('develop', function () {
nodemon({ script: 'app.js', ext: 'html js' })
.on('restart', function () {
console.log('restarted!')
})
})
回答by xpepermint
回答by pspi
To livereload both front and backend changes to the browser. There is also the option of not using Gulp. Then, the right combination of packages is 'livereload', 'connect-livereload', and a little help from 'nodemon'. Here's how they team up:
实时重新加载浏览器的前端和后端更改。也可以选择不使用 Gulp。然后,正确的软件包组合是“livereload”、“connect-livereload”和“nodemon”的一些帮助。以下是他们如何组队:
livereloadopens a high port and notifies the browser of changed public filesconnect-livereloadmonkey patches every served HTML page with a snippet that connects to this high portnodemonis then used to restart the server on changed backend files
livereload打开一个高端口并通知浏览器更改的公共文件connect-livereload猴子使用连接到此高端口的代码段修补每个提供的 HTML 页面nodemon然后用于在更改的后端文件上重新启动服务器
Set up livereload in Express
在 Express 中设置 livereload
You'll want to set up the Express to both start livereload server watching the public directory and ping the browser during nodemon-induced restart:
您需要设置 Express 以启动 livereload 服务器以监视公共目录并在 nodemon 引起的重启期间 ping 浏览器:
const livereload = require("livereload");
const connectLivereload = require("connect-livereload");
// open livereload high port and start to watch public directory for changes
const liveReloadServer = livereload.createServer();
liveReloadServer.watch(path.join(__dirname, 'public'));
// ping browser on Express boot, once browser has reconnected and handshaken
liveReloadServer.server.once("connection", () => {
setTimeout(() => {
liveReloadServer.refresh("/");
}, 100);
});
const app = express();
// monkey patch every served HTML so they know of changes
app.use(connectLivereload());
Start Express with nodemon
使用 nodemon 启动 Express
Then you'd start the server with nodemon, for example, with a dedicated watch script npm run watch.
然后,您将使用 nodemon 启动服务器,例如,使用专用的 watch script npm run watch。
The key point here is to ignore the public directory that's already being watched by livereload. You can also configure files with non-default extensions, like pug and mustache, to be watched.
这里的关键点是忽略已经被 livereload 监视的公共目录。您还可以配置具有非默认扩展名的文件,例如 pug 和 mustache,以进行监视。
"scripts": {
"start": "node ./bin/www",
"watch": "nodemon --ext js,pug --ignore public"
},
You can read a longer explanation in "Refresh front and backend changes to browser with Express, LiveReload and Nodemon."
您可以在“使用 Express、LiveReload 和 Nodemon 刷新浏览器的前端和后端更改”中阅读更长的解释。
回答by Arvind Sridharan
You can see the setup I used at http://github.com/arvsr1988/gulp-expressjs-setup
你可以在http://github.com/arvsr1988/gulp-expressjs-setup看到我使用的设置

