我已经使用BrowserSync为我的项目编写了一个监视任务,但我遇到了一个我似乎无法弄清楚的障碍。该任务并不太疯狂,监视文件然后重新加载浏览器并根据需要编译 sass 或 js(browserify)。
问题是当我保存一个 js 文件时(比如,app.js
)它会刷新浏览器,然后编译 js 并创建bundle.js
文件,然后还会触发浏览器刷新。所以我总是得到至少 2 次刷新。有时它甚至会循环刷新 10-15 次。
对我来说最完美的是能够禁用自动刷新并自己触发它,这样我就可以保持我的逻辑进行编译,然后在过程完成后我可以触发浏览器刷新。
BrowserSync 有一种触发刷新的方法,但是我怎样才能阻止默认刷新的发生呢?
下面包含的 Js,还请注意我不想包含更多的模块,如 watchify 或任何东西。
// Dependancies
// ---------------------------
var browserSync = require("browser-sync");
var sass = require('node-sass');
var fs = require('fs');
var sys = require('sys');
var exec = require('child_process').exec;
var chalk = require('chalk');
// Used to create & listen for events
var emit = browserSync.emitter;
// Start BrowserSync
browserSync({
files: [
'views/**',
'assets/js/**',
'assets/sass/**'
],
proxy: "localhost:8080",
ghostMode: false,
open: false,
port: 9090,
watchOptions: {
reloadDelay: 1000,
debounceDelay: 1000
}
});
// When a file is changed
emit.on("file:changed", function (res) {
// On file save, the `file:changed` event is fired twice.
// Only listen for the `core` response.
if(res.namespace !== 'core') return false;
// File extention
var ext = res.path.split('.').pop();
// Emit the compile events when appropriate
switch(ext){
case 'scss':
emit.emit('compile-sass');
break;
case 'js':
emit.emit('compile-js');
break;
}
});
// Compile Sass Event
emit.on("compile-sass", function(){
sass.render({
file: 'assets/sass/styles.scss',
outFile: 'assets/css/styles.css',
sourceMap: true,
sourceMapEmbed: true,
outputStyle: 'compressed',
success: function(result) {
console.log("[" + chalk.blue('SS') + "] " + chalk.cyan("Watch:") + " Sass -> Css Compiling Successful");
// Write the results to the css file
fs.writeFile("assets/css/styles.css", result.css, function(err) {
if(!err) return console.log("[" + chalk.blue('SS') + "] " + chalk.cyan("Watch:") + chalk.magenta(' styles.css') + " saved successfully");
console.log("[" + chalk.blue('SS') + "] " + chalk.cyan("Watch:") + "There was an error writing to styles.css", err);
});
}
});
});
// Compile Js Event
emit.on("compile-js", function(){
exec("browserify assets/js/app.js -o assets/js/bundle.js --debug", function (err, stdout, stderr) {
if(err) throw err;
console.log("[" + chalk.blue('SS') + "] " + chalk.cyan('Watch:') + chalk.magenta(' bundle.js') + ' successfully created');
});
});