如何在Gulpfile中修复浏览器同步和实时重新加载?

时间:2018-12-14 19:16:27

标签: gulp browser-sync gulp-watch livereload

我正在尝试使gulp文件中的Browser Sync和Live Reload正常工作,但是它不想正常运行。

我希望能够检测根目录中都包含的'src'和'templates'文件夹中的任何文件更改。 gulp文件可以很好地检测src文件夹中的更改,但是保存时不会在浏览器中重新加载模板文件。

注意:

  • 我有实时重新加载chrome浏览器扩展程序。
  • 我不是编译模板文件夹,而是将src中的所有内容编译到Web目标文件夹。

Gulp文件:

// -------------------- Configuration Settings --------------------
var config = {};

//basics
config.siteName = 'Franklin';
config.proxyDomain = 'https://franklin.test';

//source directory
config.src = 'src/';

//twig templates
config.templates = 'templates';

//destinations
config.dest = 'web/';
config.destJS = config.dest + 'assets/js';
config.destCSS = config.dest + 'assets/css';
config.destFonts = config.dest + 'assets/fonts';
config.destPWA = config.dest;

//globs
config.globs = {
    templates : config.templates + '/**/*.twig',
    scss : config.src + 'scss/**/*.scss',
    js : {
        individual : config.src + 'js/individual/**/*.js',
        combined : [
            config.src + 'js/combined/libs/*.js',
            config.src + 'js/combined/plugins/*.js',
            config.src + 'js/combined/pluginSubs/*.js',
            config.src + 'js/combined/site/*.js',
            config.src + 'js/combined/site.js'
        ]
    },
    fonts : config.src + 'fonts/**/*',
    pwa : config.src + 'pwa/**/*',
    watched : [
        config.templates + '/**/*.twig',
        config.destJS + '/**/*.min.js',
        config.destCSS + '/**/*.min.css',
        config.destFonts + '/**/*',
        config.destPWA + '/**/*'
    ]
};

//browser sync
config.browserSync = {
    files: config.globs.watched,
    proxy: config.proxyDomain
};

// -------------------- Require Statements --------------------
var gulp           = require('gulp'),
    autoprefixer     = require('gulp-autoprefixer'),
    concat           = require('gulp-concat'),
    livereload       = require('gulp-livereload'),
    browserSync      = require('browser-sync').create(),
    newer            = require('gulp-newer'),
    notify           = require('gulp-notify'),
    plumber          = require('gulp-plumber'),
    rename           = require('gulp-rename'),
    sass             = require('gulp-sass'),
    size             = require('gulp-size'),
    uglify           = require('gulp-uglify'),
    watch            = require('gulp-watch'),
    path             = require('path'),
    cssnano          = require('gulp-cssnano'),
    sourcemaps       = require('gulp-sourcemaps'),
    lazypipe         = require('lazypipe'),
    fs               = require('fs');

// -------------------- Notification Icon Detection --------------------
/**
 * Checks to see if a file exists.
 *
 * @param filePath
 * @returns {*}
 */
function fileExists(filePath)
{
    try {
        return fs.statSync(filePath).isFile();
    } catch (err) {
        return false;
    }
}

var iconPath = path.join(__dirname, 'gulp.png');
var icon = fileExists( iconPath ) ? iconPath : null;

// -------------------- Plumber Error Handler --------------------
var plumberErrorHandler = function(err) {
    console.log( 'plumber error! "' + err.message + '"' );
    notify.onError({
        title: config.siteName,
        message: "Error: <%= err.message %>",
        sound: 'Pop'
    });
    this.emit('end');
};

// -------------------- Processors --------------------
//individual scripts (not combined)
var jsIndividualScripts = lazypipe()
    .pipe(plumber, {errorHandler: plumberErrorHandler})
    .pipe(newer, { dest: config.destJS, ext: '.min.js' })
    .pipe(gulp.dest, config.destJS)
    .pipe(size, {showFiles: true})
    .pipe(uglify)
    .pipe(rename, { suffix: '.min' })
    .pipe(gulp.dest, config.destJS)
    .pipe(size, {showFiles: true});

//combined scripts
var jsCombinedScripts = lazypipe()
    .pipe(plumber, {errorHandler: plumberErrorHandler})
    .pipe(newer, config.dest + 'js/scripts.min.js')
    .pipe(concat, 'scripts.js')
    .pipe(gulp.dest, config.destJS)
    .pipe(size, {showFiles: true})
    .pipe(uglify)
    .pipe(rename, { suffix: '.min' })
    .pipe(gulp.dest, config.destJS)
    .pipe(size, {showFiles: true});

//scss compiling
var scssProcessing = lazypipe()
    .pipe(plumber, {errorHandler: plumberErrorHandler})
    .pipe(sass, {outputStyle: ':compact'})
    .pipe(autoprefixer, 'last 2 version')
    .pipe(gulp.dest, config.destCSS)
    .pipe(size, {showFiles: true})
    .pipe(rename, { suffix: '.min' })
    .pipe(sourcemaps.init)
    .pipe(cssnano)
    .pipe(sourcemaps.write, '.')
    .pipe(gulp.dest, config.destCSS)
    .pipe(size, {showFiles: true});

//fonts compiling
var fontsProcessing = lazypipe()
    .pipe(plumber, {errorHandler: plumberErrorHandler})
    .pipe(gulp.dest, config.destFonts);

//pwa compiling
var pwaProcessing = lazypipe()
    .pipe(plumber, { errorHandler: plumberErrorHandler })
    .pipe(gulp.dest, config.destPWA);


// -------------------- Tasks --------------------
//styles task
gulp.task('styles', function() {
    if ( browserSync.active ) {
        return gulp.src(config.globs.scss)
            .pipe(scssProcessing())
            .pipe(browserSync.reload({stream:true}));
    }
    return gulp.src(config.globs.scss).pipe(scssProcessing());
});

//template task
gulp.task('templates', function() {
    if ( browserSync.active ) {
        return gulp.src(config.globs.templates)
            .pipe(browserSync.reload({stream:true}));
    }
});

//scripts individual task
gulp.task('scripts-individual', function() {
    return gulp.src(config.globs.js.individual).pipe(jsIndividualScripts());
});

//scripts combined task
gulp.task('scripts-combined', function() {
    return gulp.src(config.globs.js.combined).pipe(jsCombinedScripts());
});

//fonts task
gulp.task('fonts', function() {
    return gulp.src(config.globs.fonts).pipe(fontsProcessing());
});

//pwa task
gulp.task('pwa', function () {
    return gulp.src(config.globs.pwa).pipe(pwaProcessing());
});

//watch task
gulp.task('live', function() {
    //watch all .scss files
    gulp.watch(config.globs.scss, ['styles']);

    //watch all twig template files
    gulp.watch(config.globs.templates, ['templates']);

    //watch each individual .js file
    watch(config.globs.js.individual).pipe(jsIndividualScripts());

    //watch all combined .js files
    gulp.watch(config.globs.js.combined, ['scripts-combined']);
});

//default task - one time styles and scripts
gulp.task('default', ['styles', 'templates', 'scripts-individual', 'scripts-combined', 'fonts', 'pwa']);

//start browser-sync server
gulp.task('serve-bs', ['live'], function() {
    browserSync.init(config.browserSync)
});

//start livereload
gulp.task('watch', ['live'], function() {
    livereload.listen();

    //watch for changes on transpired templates, css, and js files
    gulp.watch(config.globs.watched, function(event) {
        gulp.src(event.path)
            .pipe(plumber({errorHandler: plumberErrorHandler}))
            .pipe(livereload())
            .pipe(notify({
                    title: config.siteName,
                    message: event.type + ': ' + event.path.replace(__dirname, '').replace(/\\/g, '/') + ' was reloaded',
                    sound: 'Pop',
                    icon: icon
                })
            );
    });
});

0 个答案:

没有答案