S
S
Sergey Karvasarny2018-11-21 22:12:04
gulp.js
Sergey Karvasarny, 2018-11-21 22:12:04

Without refreshing the page, the site does not start from the server - browser-sync, how to fix it?

I've looked all over and can't figure out what's going on. The project compiles without any problems, starts the server and every time I see there - Cannot GET /, press F5 and everything works and so every time, I tried to comment libs-script: build in the build and watch, it almost always starts, but it happens that pictures It doesn’t load, randomly about half, although the paths to them are correct and they are in the folders, F5 also works, what kind of glitches are these? it feels like the server starts without finishing the compilation, but everything seems to be in time on the command line.
5bf5adc45aaf1634064471.png

gulpfile.js
var gulp = require('gulp'), // подключаем Gulp
    sass = require('gulp-sass'), // модуль для компиляции SASS (SCSS) в CSS
    webserver = require('browser-sync'), // сервер для работы и автоматического обновления страниц
    del = require('del'), // плагин для удаления файлов и каталогов
    cache = require('gulp-cache'), // модуль для кэширования
    autoprefixer = require('gulp-autoprefixer'), // модуль для автоматической установки автопрефиксов
    uglify = require('gulp-uglifyjs'), // модуль для минимизации JavaScript
    imagemin = require('gulp-imagemin'), // плагин для сжатия PNG, JPEG, GIF и SVG изображений
    rigger = require('gulp-rigger'), // модуль для импорта содержимого одного файла в другой
    jpegrecompress = require('imagemin-jpeg-recompress'), // плагин для сжатия jpeg	
    notify = require('gulp-notify'), // модуль для отслеживания ошибок
    pngquant = require('pngquant'), // плагин для сжатия png
    sourcemaps = require('gulp-sourcemaps'), // модуль для генерации карты исходных файлов

    importCss = require('gulp-import-css'),
    concat = require('gulp-concat'),
    cssNano = require('gulp-cssnano'), // плагин для минимизации CSS
    rename = require('gulp-rename'); // плагин для переименования

var autoprefixerList = [
  'Chrome >= 45',
  'Firefox ESR',
  'Edge >= 12',
  'Explorer >= 10',
  'iOS >= 9',
  'Safari >= 9',
  'Android >= 4.4',
  'Opera >= 30'
];

var path = {
  build: {
    html:    'build/',
    js:      'build/js/',
    css:     'build/css/',
    img:     'build/images/',
    fonts:   'build/webfonts/'
  },
  src: {
    html:    'app/*.html',
    js:      'app/js/*.js',
    libsJs:  'app/libs/include.js',
    css:     'app/css/main.scss',
    libsCss: 'app/libs/include.css',
    sass:    'app/sass/style.scss',
    img:     'app/images/**/*.*',
    fonts:   'app/webfonts/**/*.*'
  },
  watch: {
    html:    'app/**/*.html',
    js:      'app/js/*.js',
    libsJs:  'app/libs/include.js',
    css:     'app/css/main.scss',
    libsCss: 'app/libs/include.css',
    img:     'app/images/**/*.*',
    fonts:   'app/webfonts/**/*.*'
  },
  clean:      './build'
};

var config = {
  server: {
    baseDir: './build'
  },
  notify: false
};



// запуск сервера
gulp.task('webserver', function () {
  webserver(config);
});

// сбор html
gulp.task('html:build', function () {
  gulp.src(path.src.html) // выбор всех html файлов по указанному пути
    .pipe(rigger()) // импорт вложений
    .pipe(gulp.dest(path.build.html)) // выкладывание готовых файлов
    .pipe(webserver.reload({stream: true})); // перезагрузка сервера
});

// сбор css
gulp.task('libs:build', function(){
  gulp.src(path.src.libsCss)
    .pipe(rename({suffix:".min"}))
    .pipe(importCss())
    .pipe(cssNano())
    .pipe(gulp.dest(path.build.css)) // выгружаем в build
});

gulp.task('css:build',function(){
  return gulp.src(path.src.sass)
    .pipe(sass().on('error', notify.onError(
    {
      message: "<%= error.message %>",
      title  : "Sass Error!"
    })))
    .pipe(autoprefixer({ // добавим префиксы
    browsers: autoprefixerList
  }))
    .pipe(cssNano())
    .pipe(sourcemaps.write('./')) // записываем sourcemap
    .pipe(gulp.dest(path.build.css)) // выгружаем в build
    .pipe(webserver.reload({stream: true})); // перезагрузим сервер
});


// сбор js
gulp.task('libs-script:build', function(){
  return gulp.src(path.src.libsJs)
    .pipe(rigger())
    .pipe(uglify())
    .pipe(gulp.dest(path.build.js))
    .pipe(webserver.reload({stream: true}));
});

gulp.task('js:build', function () {
  return gulp.src(path.src.js)
    .pipe(gulp.dest(path.build.js))
    .pipe(webserver.reload({stream: true})); // перезагрузим сервер
});


// перенос шрифтов
gulp.task('fonts:build', function() {
  gulp.src(path.src.fonts)
    .pipe(gulp.dest(path.build.fonts));
});

// обработка картинок
gulp.task('image:build', function () {
  gulp.src(path.src.img) // путь с исходниками картинок
    .pipe(cache(imagemin([ // сжатие изображений
    imagemin.gifsicle({interlaced: true}),
    jpegrecompress({
      progressive: true,
      max: 90,
      min: 80
    }),
    pngquant(),
    imagemin.svgo({plugins: [{removeViewBox: false}]})
  ])))
    .pipe(gulp.dest(path.build.img)); // выгрузка готовых файлов
});


// удаление каталога build 
gulp.task('clean:build', function () {
  del.sync(path.clean);
});

// очистка кэша
gulp.task('cache:clear', function () {
  cache.clearAll();
});

// сборка
gulp.task('build', [
  'clean:build',
  'html:build',
  'libs:build',
  'css:build',
  'libs-script:build',
  'js:build',
  'fonts:build',
  'image:build'
]);

// запуск задач при изменении файлов
gulp.task('watch', function() {
  gulp.watch(path.watch.html, ['html:build']);
  gulp.watch(path.watch.html, ['libs:build']);
  gulp.watch(path.watch.css, ['css:build']);
  gulp.watch(path.watch.js, ['libs-script:build']);
  gulp.watch(path.watch.js, ['js:build']);
  gulp.watch(path.watch.img, ['image:build']);
  gulp.watch(path.watch.fonts, ['fonts:build']);
});

// задача по умолчанию
gulp.task('default', [
  'clean:build',
  'build',
  'webserver',
  'watch'
]);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey delphinpro, 2018-11-22
@megapihar6

All your tasks are running in parallel. It is better to start the server and the watcher after the rest of the tasks are completed.
If you have a third gulp, use the gulp-sequence package to run the tasks again. The four have built-in tools.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question