0

Being new to gulp. I have the follwing task. I need to spawn a webserver and then another script has to run some stuff against this webserver. I am currently struggling with finishing the script because the browser-sync task does not finish and prevents the script from exit.

'use strict';

const browserSync = require('browser-sync').create();
const cp = require('child_process');
const minimalcss = require('minimalcss');

const gulp = require('gulp');

const clean = require('gulp-clean');

const sourceDir = "_site/";
const deployDir = "public/";

// build the mkdocs Site
gulp.task('build', function() {
  return cp.exec('pipenv run mkdocs build --site-dir ' + sourceDir);
});

// Delete _deploy directory first
gulp.task('prepare', function() {
  return gulp.src(deployDir, {read: false, allowEmpty: true})
      .pipe(clean());
});

// Delete _deploy directory again  // just for testing
gulp.task('cleanup', function() {
  return gulp.src(deployDir, {read: false, allowEmpty: true})
      .pipe(clean());
});

// does not lead to anything, just for testing
gulp.task('inlinecriticalCSS', function(done) {
  minimalcss
    .minimize({ urls: ['http://localhost:9999/' + 'index.html'] })
    .then(result => {
    console.log('OUTPUT', result.finalCss.length, result.finalCss);
  })
  .catch(error => {
    console.error(`Failed the minimize CSS: ${error}`);
  });
  done();
});

// webserver
gulp.task('serve', (done) => {
  browserSync.init({
    port: 9999,
    server: {
      baseDir: sourceDir
    }
  });
  done();
});

// default sequence
gulp.task('default', gulp.series(
  'prepare', 
  'build', 
  'serve',
  'inlinecriticalCSS',
  'cleanup')
);
Gerald Bäck
  • 445
  • 1
  • 5
  • 7
  • You would typically leave the `browser-sync` task open, no? Perhaps you could run the serve in parallel instead? `gulp.task('default', gulp.series('prepare', 'build', gulp.parallel('serve', gulp.series('inlinecriticalCSS', 'cleanup'))))` (just as an illustration, the formatting is obviously not very readable) – Derek Nguyen Jan 10 '19 at 09:08
  • thanks, is there a way to stop the task from another task? – Gerald Bäck Jan 10 '19 at 12:27
  • Yes, you can call `browserSync.exit()` in other tasks. It will close any current running server. – Derek Nguyen Jan 10 '19 at 12:39

0 Answers0