S
S
Sergey Novikov2020-05-03 13:21:25
gulp.js
Sergey Novikov, 2020-05-03 13:21:25

Need to convert gulp3.js to gulp4.js can anyone help?

there is a file for the 3rd gallp, you need to redo it for the 4th gallp. can anyone fix it? text here

gulpfile.js
'use strict';

    var gulp = require('gulp'),
    mainBowerFiles = require('main-bower-files'),
    watch = require('gulp-watch'),
    prefixer = require('gulp-autoprefixer'),
    uglify = require('gulp-uglify'),
    sourcemaps = require('gulp-sourcemaps'),
    sass = require('gulp-sass'),
    cleanCSS = require('gulp-clean-css'),
    imagemin = require('gulp-imagemin'),
    pngquant = require('imagemin-pngquant'),
    rimraf = require('rimraf'),
    browserSync = require("browser-sync"),
    reload = browserSync.reload;


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



var config = {
    server: {
        baseDir: "./dist"
    },
    tunnel: true,
    host: 'localhost',
    port: 8081,
    logPrefix: "Morphei"
};



gulp.task('vendorJs:build', function () {
    gulp.src( mainBowerFiles('**/*.js') ) //Выберем файлы по нужному пути
        .pipe(gulp.dest(path.vendor.js)) //Выплюнем готовый файл в app
});

gulp.task('vendorCss:build', function () {
    gulp.src( mainBowerFiles('**/*.css') ) //Выберем файлы по нужному пути
        .pipe(gulp.dest(path.vendor.css)) //И в app
});

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

gulp.task('js:build', function () {
    gulp.src(path.app.js) //Найдем наш main файл
        .pipe(sourcemaps.init()) //Инициализируем sourcemap
        .pipe(uglify()) //Сожмем наш js
        .pipe(sourcemaps.write()) //Пропишем карты
        .pipe(gulp.dest(path.dist.js)) //Выплюнем готовый файл в build
        .pipe(reload({stream: true})); //И перезагрузим сервер
});

gulp.task('scss:build', function () {
    gulp.src(path.app.scss) //Выберем наш main.scss
        .pipe(sourcemaps.init()) //То же самое что и с js
        .pipe(sass()) //Скомпилируем
        .pipe(prefixer()) //Добавим вендорные префиксы
        .pipe(cleanCSS()) //Сожмем
        .pipe(sourcemaps.write())
        .pipe(gulp.dest(path.dist.scss)) //И в build
        .pipe(reload({stream: true}));
});

gulp.task('css:build', function () {
    gulp.src(path.app.css) //Выберем наш main.css
        .pipe(sourcemaps.init()) //То же самое что и с js
        .pipe(gulp.dest(path.dist.css)) //И в build
        .pipe(reload({stream: true}));
});

gulp.task('image:build', function () {
    gulp.src(path.app.img) //Выберем наши картинки
        .pipe(imagemin({ //Сожмем их
            progressive: true,
            svgoPlugins: [{removeViewBox: false}],
            use: [pngquant()],
            interlaced: true
        }))
        .pipe(gulp.dest(path.dist.img)) //И бросим в build
        .pipe(reload({stream: true}));
});

gulp.task('fonts:build', function() {
    gulp.src(path.app.fonts)
        .pipe(gulp.dest(path.dist.fonts))
});

gulp.task('build', [
    'vendorCss:build',
    'vendorJs:build',
    'html:build',
    'js:build',
    'scss:build',
    'css:build',
    'fonts:build',
    'image:build'
]);

gulp.task('watch', function(){
    watch([path.watch.html], function(event, cb) {
        gulp.start('html:build');
    });
    watch([path.watch.scss], function(event, cb) {
        gulp.start('scss:build');
    });
    watch([path.watch.css], function(event, cb) {
        gulp.start('css:build');
    });
    watch([path.watch.js], function(event, cb) {
        gulp.start('js:build');
    });
    watch([path.watch.img], function(event, cb) {
        gulp.start('image:build');
    });
    watch([path.watch.fonts], function(event, cb) {
        gulp.start('fonts:build');
    });
});


gulp.task('webserver', function () {
    browserSync(config);
});


gulp.task('clean', function (cb) {
    rimraf(path.clean, cb);
});


gulp.task('default', ['build', 'webserver', 'watch']);

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2020-05-03
@Morphei112

Taska

gulp.task('task-name', () => {
    return gulp.src(...)
        .pipe(gulp.dest(...));
});

Change the task buildto
gulp.task('build:vendor', gulp.parallel('vendorCss:build', 'vendorJs:build'));

gulp.task('build:sources', gulp.parallel('html:build', 'js:build', 'scss:build', 'css:build', 'fonts:build', 'image:build');

gulp.task('build', gulp.series('build:vendor', 'build:sources'));

Change the cleanup task to this ( del package )
gulp.task('clean', () => {
    return del(path.clean);
});

Server task
gulp.task('webserver', (callback) => {
    browserSync(config);

    callback();
});

Launch task
gulp.task('default', gulp.series('build', 'webserver', 'watch'));

UPD :
Learn

const fs = require('fs');
const path = require('path');
const gulp = require('gulp');
const pipeIf = require('gulp-if');
const nunjucks = require('gulp-nunjucks');
const pretty = require('gulp-pretty-html');
const minify = require('gulp-htmlmin');
const replace = require('gulp-replace');
const sass = require('gulp-sass');
const sourcemaps = require('gulp-sourcemaps');
const autoprefixer = require('gulp-autoprefixer');
const clean = require('gulp-clean-css');
const rollup = require('rollup');
const resolve = require('@rollup/plugin-node-resolve');
const commonjs = require('@rollup/plugin-commonjs');
const babel = require('rollup-plugin-babel');
const { terser } = require('rollup-plugin-terser');
const image = require('gulp-image');
const clear = require('gulp-clean');
const browser = require('browser-sync').create();
const { argv } = require('yargs');

sass.compiler = require('node-sass');

const getFiles = dirname => {
  const entries = fs.readdirSync(dirname);
  const files = entries
    .filter(entry => {
      const stat = fs.statSync(path.join(dirname, entry));

      return stat.isFile();
    })
    .reduce((accumulator, file) => {
      const name = path.basename(file, path.extname(file));
      accumulator[name] = path.join(dirname, file);

      return accumulator;
    }, {});

  return files;
};

const scripts = getFiles('Sources/Scripts/');

gulp.task('server', (callback) => {
  browser.init({
    server: {
      baseDir: 'Build'
    },
    ui: {
      port: 8080
    },
    notify: false
  });

  callback();
});

gulp.task('reload', (callback) => {
  browser.reload();

  callback();
});

gulp.task('clear', () => {
  return gulp.src('Build', { allowEmpty: true })
    .pipe(clear({
      force: true
    }));
});

gulp.task('build:html', () => {
  return gulp.src('Sources/**/*.html')
    .pipe(nunjucks.compile())
    .pipe(replace(/(\r\n|\r|\n)(\s+)?(\r\n|\r|\n)/gm, '\n'))
    .pipe(pipeIf(argv.development, pretty({
      indent_with_tabs: true,
      extra_liners: []
    })))
    .pipe(pipeIf(argv.production, minify({
      collapseWhitespace: true
    })))
    .pipe(gulp.dest(`Build/`));
});

gulp.task('build:sass', () => {
  return gulp.src(['Sources/Styles/*.sass', 'Sources/Styles/*.scss'])
    .pipe(pipeIf(argv.development, sourcemaps.init()))
    .pipe(pipeIf(argv.development, sass({
      indentWidth: 4,
      outputStyle: 'expanded'
    })))
    .pipe(pipeIf(argv.production, sass()))
    .pipe(autoprefixer({
      cascade: false
    }))
    .pipe(pipeIf(argv.production, clean()))
    .pipe(pipeIf(argv.development, sourcemaps.write('.')))
    .pipe(gulp.dest('Build/Styles/'));
});

gulp.task('build:js', async (callback) => {
  const bundle = await rollup.rollup({
    input: scripts,
    plugins: [
      resolve(),
      commonjs(),
      babel({
        exclude: 'node_modules/**',
        presets: ['@babel/env']
      }),
      !!argv.production && terser({
        keep_classnames: true
      })
    ]
  });

  await bundle.write({
    dir: 'Build/Scripts/',
    format: 'esm',
    chunkFileNames: '[name].js',
    entryFileNames: '[name].js',
    sourcemap: !!argv.development
  });

  callback();
});

gulp.task('build:images', () => {
  return gulp.src(['Sources/Images/**/*.png', 'Sources/Images/**/*.jpg', 'Sources/Images/**/*.svg'])
    .pipe(pipeIf(argv.production, image()))
    .pipe(gulp.dest('Build/Images/'));
});

gulp.task('watch:html', () => {
  gulp.watch(['Sources/**/*.html', 'Sources/**/*.njk'], gulp.series('build:html', 'reload'));
});

gulp.task('watch:sass', () => {
  gulp.watch(['Sources/Styles/**/*.sass', 'Sources/Styles/**/*.scss'], gulp.series('build:sass', 'reload'));
});

gulp.task('watch:js', () => {
  gulp.watch('Sources/Scripts/**/*.js', gulp.series('build:js', 'reload'));
});

gulp.task('watch:images', () => {
  gulp.watch(['Sources/Images/**/*.png', 'Sources/Images/**/*.jpg', 'Sources/Images/**/*.svg'], gulp.series('build:images'));
});

gulp.task('watch:icons', () => {
  gulp.watch('Sources/Icons/**/*.svg', gulp.series('build:html', 'reload'));
});

gulp.task('build', gulp.parallel('build:html', 'build:sass', 'build:js', 'build:images'));

gulp.task('watch', gulp.parallel('watch:html', 'watch:sass', 'watch:js', 'watch:images', 'watch:icons'));

gulp.task('default', gulp.series('clear', 'build', 'server', 'watch'));

S
Sergey Novikov, 2020-05-03
@Morphei112

E:\template\gulpfile.js:69
gulp.task('build:vendor', gulp.parallel('vendorCss:build', 'vendorJs:build') {
^
SyntaxError: missing ) after argument list
at wrapSafe (internal/ modules/cjs/loader.js:1047:16)
at Module._compile (internal/modules/cjs/loader.js:1097:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js :1153:10)
at Module.load (internal/modules/cjs/loader.js:977:32)
at Function.Module._load (internal/modules/cjs/loader.js:877:14)
at Module.require ( internal/modules/cjs/loader.js:1019:19)
at require (internal/modules/cjs/helpers.js:77:18)
at execute (C:\Users\sergey\AppData\Roaming\npm\node_modules\gulp\node_modules\gulp-cli\lib\versioned\^4.0.0\index.js:36:18)
at Liftoff.handleArguments (C: \Users\sergey\AppData\Roaming\npm\node_modules\gulp\node_modules\gulp-cli\index.js:201:24)
at Liftoff.execute (C:\Users\sergey\AppData\Roaming\npm\node_modules\gulp \node_modules\liftoff\index.js:201:12)
got the following error

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question