0

Пробую перейти на новые стандарты gulp, переписал свой

package.json

     {
  "name": "startpage",
  "version": "3.0.0",
  "description": "Start page for site",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Zirka Andry",
  "devDependencies": {
    "browser-sync": "^2.26.7",
    "gulp": "^4.0.2",
    "gulp-autoprefixer": "^7.0.1",
    "gulp-clean": "^0.4.0",
    "gulp-combine-mq": "^0.4.0",
    "gulp-concat": "^2.6.1",
    "gulp-csso": "^4.0.1",
    "gulp-if": "^3.0.0",
    "gulp-imagemin": "^7.1.0",
    "gulp-rename": "^2.0.0",
    "gulp-sass": "^4.0.2",
    "gulp-uglify-es": "^2.0.0",
    "gulp-useref": "^4.0.1",
    "gulp.spritesmith": "^6.11.0",
    "imagemin-pngquant": "^8.0.0",
    "main-bower-files": "^2.13.3"
  }
}

и gulpfile.js Фаил

//Подключаем модули галпа
const gulp = require("gulp"),                             // gulp core
      sass = require('gulp-sass'),                        // sass compiler
      gulpif = require('gulp-if'),                        // conditionally run a task
      clean = require('gulp-clean'),                      // removing files and folders
      uglify = require('gulp-uglify-es').default,         // uglifies the js

      concat = require('gulp-concat'),
      rename = require('gulp-rename'),                    // rename files
      useref = require('gulp-useref'),                    // parse build blocks in HTML files to replace references

      csso = require('gulp-csso'),                        // minify the css files
      cmq = require('gulp-combine-mq'),


      autoprefixer = require('gulp-autoprefixer'),        // sets missing browserprefixes
      browserSync = require('browser-sync').create(),     // inject code to all devices
      imagemin = require('gulp-imagemin'),                // minify images
      pngquant = require('imagemin-pngquant'),            // minify png-format images
      spritesmith = require('gulp.spritesmith'),          // create sprites

      htmlnano = require('gulp-htmlnano'),
      options = {removeComments: false};


/*********************************************/
/*WATCHER (WATCHING FILE CHANGES)*/
/*********************************************/


gulp.task('watch', function () {
    gulp.watch(['./app/**/*.html'], ['html']);          // watching changes in HTML
    gulp.watch(['./app/sass/**/*.scss'], ['sass']);     // watching changes in SASS
    gulp.watch(['./app/libs/defaultPluginStyles.css'], ['sass']);     // watching changes in SASS
    gulp.watch(['./app/js/**/*.js'], ['js']);           // watching changes in JS
    gulp.watch(['./app/image/sprite/*.*'], ['sprite']);   // watching changes in IMAGES
});

/*********************************************/
/*HTML TASKS*/
/*********************************************/

gulp.task('html', function () {
    gulp.src('./app/index.html')                        // get the files
        .pipe(gulp.dest('./app/'))                      // where to put the file
        .pipe(browserSync.stream());                    // browsersync stream
});

/*********************************************/
/*SASS TASKS*/
/*********************************************/

gulp.task('sass', ['sprite'], function () {
    gulp.src('./app/sass/**/*')                         // get the files
        .pipe(sass().on('error', sass.logError))        // add prefixes
        .pipe(autoprefixer({
            browsers: ['last 7 versions'],
            cascade: true
        }))
        .pipe(cmq())
        .pipe(csso())
        .pipe(gulp.dest('app/css'))                     // where to put the file
        .pipe(browserSync.stream());                    // browsersync stream
});

/*********************************************/
/*JS TASKS*/
/*********************************************/

gulp.task('js', function () {
    return gulp.src('./app/js/*.js')                 // get the files
        .pipe(browserSync.stream())
    // browsersync stream
});

/*********************************************/
/*IMAGES TASKS*/
/*********************************************/

gulp.task('sprite', function (done) {
    buildSprite().on('end', done);
});

gulp.task('images', ['sprite'], function () {
    return gulp.src('./app/image/**/*')                   // get the files
        .pipe(imagemin({                                // minify images
            progressive: true,
            svgoPlugins: [{
                removeViewBox: false
            }, {
                cleanupIDs: false
            }],
            use: [pngquant({                            // minify png-format images
                quality: '50-70',
                speed: 4
            })],
            interlaced: true

        }))
        .pipe(gulp.dest('dist/image'));                   // where to put the files
});

/*********************************************/
/*FONTS TASKS*/
/*********************************************/

gulp.task('fonts', function () {
    return gulp.src('./app/fonts/**/*')                 // get the files
        .pipe(gulp.dest('dist/fonts'));                 // where to put the files
});

/*********************************************/
/*LIBS TASKS (PERSONAL DEVELOPER LIBS)*/
/*********************************************/

gulp.task('libs', function () {
    return gulp.src('./app/libs/**/*')                  // get the files
        .pipe(gulp.dest('dist/libs'));                  // where to put the files
});

/*********************************************/
/*EXTRASS TASKS (ROOT FILES, EXCEPT HTML)*/
/*********************************************/

gulp.task('extrass', function () {
    return gulp.src([                                   // get the files
        'app/*.*',
        '!app/*.html'                                   // except '.html'
    ]).pipe(gulp.dest('dist'));                         // where to put the files
});


/*********************************************/
/*BUILD TASKS*/
/*********************************************/

gulp.task('clean', function () {
    return gulp.src('dist', {read: false})
        .pipe(clean());                                 // clean dir
});


gulp.task('build', ['clean'], function () {
    gulp.start('images');                               // images task
    gulp.start('fonts');                                // fonts task
    gulp.start('libs');                                 // libs task
    gulp.start('extrass');                              // extras task

    return gulp.src('app/*.html')
        .pipe(gulpif('app/*.js', uglify()))   // uglify js-files
        .pipe(gulpif('app/*.css', csso()))    // minify css-files
        .pipe(useref())
        .pipe(gulp.dest('./dist'));                     // where to put the files
});

/*********************************************/
/*FUNCTIONS*/
/*********************************************/

function buildSprite() {
    var spriteData = gulp.src('./app/image/sprite/*.*')
        .pipe(spritesmith({
            imgName: '../image/sprite.png',
            cssName: '_sprite.scss',
            cssFormat: 'scss',
            padding: 5
        }));

    spriteData.img.pipe(gulp.dest('./app/image'));
    return spriteData.css.pipe(gulp.dest('./app/sass/components'));
}

/*********************************************/
/*MINIMIZATION JS*/
/*********************************************/
gulp.task('jsmin', function(){
    gulp.src(['./app/js/*.js'])
        .pipe(concat('common.js'))
        .pipe(uglify())
        .pipe(rename("./common-xmin.js"))
        .pipe(gulp.dest('app/js'));
});


/*********************************************/
/*MINIMIZATION HTML*/
/*********************************************/
gulp.task('htmlmin', function() {
    return gulp
        .src('dist/*.html')
        .pipe(htmlnano(options))
        .pipe(gulp.dest('./dist'));
});

/*********************************************/
/*BROWSERSYNC (LOCAL SERVER)*/
/*********************************************/

gulp.task('default', ['watch'], function () {           // start server
    browserSync.init({
        server: {baseDir: "./app/"}                     // base dir
    });
});

но всё резко перестало работать. Ломается с ошибкой const { Math, Object } = primordials; ^ReferenceError: primordials is not defined На форумах пишут про несовместимость версий npm gulp node-js разных версий, но попробовал реализовать простые таски, всё работает. Значит косяк где-то в gulp.js Подскажите, пожалуйста, где я допускаю ошибку при переходе на новую версию?

7
  • Попробуйте gulp-uglify-es вместо gulp-uglify
    – borodatych
    24 янв 2020 в 10:14
  • заменил, к сожалению проблема не ушла. 25 янв 2020 в 11:24
  • я тоже так же переходил на gulp4 и делал всё по инструкции .. хотите ознакомиться ? 25 янв 2020 в 13:13
  • @MaximLensky да, конечно если это сможет помочь. Просто, простые gulp pipe-s у меня отрабатывают, да и под чужие сборщики, тоже запускаются, но вот под свои задачи мне нужно воcстановить работоспособность данного таск-менеджера. А моих знаний не хватает, что б разобраться в чём происходит ошибка 25 янв 2020 в 14:32
  • просто проверь - если поможет напиши - youtu.be/r2S423N-ETA 25 янв 2020 в 14:38

1 ответ 1

-1

Gulp.js 4.0 представляет методы series() and parallel() для объединения задач

Gulp.js 3 позволял указывать массивы синхронных задач. Gulp.js 4.0 важно когда задача завершена, чтобы управлять

https://webformyself.com/kak-perejti-na-gulp-js-4-0/

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.