本节将介绍node-webkit敏捷开发的一些解决方案。
功能:只需你在js编辑器中进行保存操作,最终结果便会同步显示在nw.exe执行程序中。(这意味着nw.exe只需打开一次且不用刷新即可看到程序修改结果)
(一)基本解决方案
你只需在你的主文件中添加以下语句,即可实现显示同步:
<script>
var path = './';
var fs = require('fs');
fs.watch(path, function() {
if (location)
location.reload();
});
</script>
(注):但这种解决方案有个缺陷,就是只能对添加该语句的同级目录文件有效果,对同级文件下的子文件无效。
(二)完美解决方案
综基本解决方案的缺点,下面提供三种能对同级文件下的子文件有同样效果的方法,及无论应用下哪个文件修改,都会同步到nw.exe显示界面中。
(1)gaze
先调用命令行从npm下载相关文件:
npm install gaze
调用语句:
<script>
var Gaze = require('gaze').Gaze;
var gaze = new Gaze('**/*');
gaze.on('all', function(event, filepath) {
if (location)
location.reload();
});
</script>
(2)chokidar
npm install chokidar
<script>
var chokidar = require('chokidar');
var watcher = chokidar.watch('.', {ignored: /[\/\\]\./});
watcher.on('all', function(event, path) {
if (location && event == "change")
location.reload();
});
</script>
(3)gulp
npm install gulp
<script>
var gulp = require('gulp');
gulp.task('reload', function () {
if (location) location.reload();
});
gulp.watch('**/*', ['reload']);
</script>
如果你不想更新整个应用而只调整CSS,你可以使用以下语句:
<script>
var gulp = require('gulp');
gulp.task('html', function () {
if (location) location.reload();
});
gulp.task('css', function () {
var styles = document.querySelectorAll('link[rel=stylesheet]');
for (var i = 0; i < styles.length; i++) {
// reload styles
var restyled = styles[i].getAttribute('href') + '?v='+Math.random(0,10000);
styles[i].setAttribute('href', restyled);
};
});
gulp.watch(['**/*.css'], ['css']);
gulp.watch(['**/*.html'], ['html']);
</script>
(三)清除node模块的缓存
清除node模块的缓存,可以使用以下代码:
for(module in global.require.cache){
if(global.require.cache.hasOwnProperty(module)){
delete global.require.cache[module];
}
}
location.reload()
(注)据部分开发者测试,用gui.APP.clearCache()和gui.Window.get().reloadIgnoringCache()方法取消缓存不可用。