E
E
Evgeniy2020-05-23 10:49:37
Node.js
Evgeniy, 2020-05-23 10:49:37

How to setup watch in gulp?

Good day to all!
Guys please help me figure out what could be the problem?

The watcher does not work, does not see the startHtml function (although it works out the norms itself), writes an error:
[10:38:08] Starting 'watchFiles'...
[10:38:08] 'watchFiles' errored after 3.18 ms
[10: 38:08] ReferenceError: startHtml is not defined

npm -v - 6.14.5
node -v - v14.3.0
gulp -v - CLI version: 2.2.1 Local version: 4.0.2

gulpfile.js looks like this

'use strict';

var gulp = require('gulp'),
    prefixer = require('gulp-autoprefixer'),
    rename = require('gulp-rename'),
    rigger = require('gulp-rigger'),
    sass = require('gulp-sass'),
    uglify = require('gulp-uglify'),
    sourcemaps = require('gulp-sourcemaps'),
    terser = require('gulp-terser'),
    nodesass = require('node-sass'),
    browserSync = require('browser-sync'),
    imagemin = require('gulp-imagemin'),
    del = require('delete'),
    reload = browserSync.reload,
    watch = require('watch');

const { series, parallel } = require('gulp');
var path = {
    build: { //Тут мы укажем куда складывать готовые после сборки файлы
        html: 'build/',
        js: 'build/js/',
        css: 'build/css/',
        img: 'build/img/',
        fonts: 'build/fonts/'
    },
    src: { //Пути откуда брать исходники
        html: 'src/*.html', //Синтаксис src/*.html говорит gulp что мы хотим взять все файлы с расширением .html
        js: 'src/js/main.js',//В стилях и скриптах нам понадобятся только main файлы
        style: 'src/sass/main.sass',
        img: 'src/img/**/*.*', //Синтаксис img/**/*.* означает - взять все файлы всех расширений из папки и из вложенных каталогов
        fonts: 'src/fonts/**/*.*'
    },
    watch: { //Тут мы укажем, за изменением каких файлов мы хотим наблюдать
        html: 'src/**/*.html',
        js: 'src/js/**/*.js',
        style: 'src/sass/**/*.sass',
        img: 'src/img/**/*.*',
        fonts: 'src/fonts/**/*.*'
    },
    clean: './build'
};

// Собираем html
exports.startHtml = function (cb) {
    return gulp.src('src/*.html')
      .pipe(rigger()) //Прогоним через rigger
      .pipe(gulp.dest(path.build.html)) //Выплюнем их в папку build
      .pipe(reload({stream: true})); //И перезагрузим наш сервер для обновлений
       cb();
};

// Изменение файлов
exports.watchFiles = function () {
  watch('./src/**/*.html', startHtml);
  cb();
}


package.json looks like this:
{
  "name": "gulp-frontend",
  "version": "1.0.0",
  "description": "",
  "main": "gulpfile.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "aithor",
  "license": "ISC",
  "devDependencies": {
    "browser-sync": "^2.26.7",
    "delete": "^1.1.0",
    "gulp": "^4.0.2",
    "gulp-autoprefixer": "^7.0.1",
    "gulp-cli": "^2.2.1",
    "gulp-imagemin": "^7.1.0",
    "gulp-rename": "^2.0.0",
    "gulp-rigger": "^0.5.8",
    "gulp-sass": "^4.1.0",
    "gulp-sourcemaps": "^2.6.5",
    "gulp-terser": "^1.2.0",
    "gulp-uglify": "^3.0.2",
    "node-sass": "^4.14.1",
    "watch": "^1.0.2"
  }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladislav Boychenko, 2020-05-23
@Zheleznov

To say that a very strange assembly is an understatement.
1. Connect browser-sync correctly:

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

2. If you use destructuring, use it correctly, why duplication?
const { series, parallel, gulp } = require('gulp');

3. If you use strict mode, why are you mixing const and var? Use only const (and let if necessary).
4. If you are using Gulp 4, you can drop the "gulp" and "task" keywords. Add "src" and "dest" to the destructuring to make it look like this:
const { series, parallel, src, dest, gulp } = require('gulp');

After that, write tasks with arrow functions and use all the delights of gulp 4, for example:
const styles = () => {
  return src('path.src.style')
    .pipe(sass())
    .pipe(autoprefixer())
    .pipe(csso())
    .pipe(dest(path.build.css))
    .pipe(browserSync.stream())
};

5. Nobody writes watchers and exports like that. Share it. You must have a separate watcher and a separate default task to launch the project. In your case, in general, it should look like this:
// Отдельно таск для работы с html
const startHtml = () => {
    return src('src/*.html')
    .pipe(rigger())
    .pipe(dest(path.build.html))
    .pipe(browserSync.stream());
};

// Отдельно через browser-sync отслеживаете изменения в html-файлах. 
const watcher = () => {
  browserSync.init({
    server: {
      baseDir: './src/'
    }, 
    notify: false
  });
    watch('./src/*.html', startHtml);
}

// Отдельно запускаете это все.
exports.default(series(startHtml, watcher));

E
Eduard07, 2020-05-23
@Eduard07

You need to create a task, for example ( [email protected] )
gulp.task('html:build', function () {
return gulp.src(path.src.html)
.pipe(gulp.dest(path.build.html) )
});
as well as a group of tasks, general
gulp.task('watch', function() {
gulp.watch(path.watch.html, ['html:build']);
});
it’s like this for me, maybe with in galpa 4 it’s not much different, but the difference there is not big, I looked.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question