G
G
Good Man2016-05-07 00:38:31
JavaScript
Good Man, 2016-05-07 00:38:31

How to set up front-end build?

Goodnight.
Once I dug up a gulpfile for the front-end build. Over time, it grew and transformed to suit my needs, supplemented ....
As a result, I got this sheet:

'use strict';

var gulp        = require('gulp'),
    watch       = require('gulp-watch'),
    prefixer    = require('gulp-autoprefixer'),
    uglify      = require('gulp-uglify'),
    sass        = require('gulp-sass'),
    sourcemaps  = require('gulp-sourcemaps'),
    rigger      = require('gulp-rigger'),
    cssmin      = require('gulp-clean-css'),
    concat      = require('gulp-concat'),
    imagemin    = require('gulp-imagemin'),
    pngquant    = require('imagemin-pngquant'),
    sprite      = require('gulp.spritesmith'),
    rimraf      = require('rimraf'),
    browserSync = require("browser-sync"),
    jade        = require('gulp-jade'),
    plumber     = require('gulp-plumber'),
    reload      = browserSync.reload;


var path = {
    build: { //Тут мы укажем куда складывать готовые после сборки файлы
        html:  'build/',
        js:    'build/js/',
        css:   'build/styles/',
        img:   'build/images/',
        fonts: 'build/fonts/'
    },
    src: { //Пути откуда брать исходники
        html:  'src/*.jade',
        js: [
            'src/js/*.js'
        ],
        style: [
          'bower_components/normalize-css/normalize.css',
          'src/style/**/*.scss',
          'src/style/**/*.css'
        ],
        img:   'src/img/*.*',
        fonts: 'src/fonts/**/*.*'
    },
    watch: { //Тут мы укажем, за изменением каких файлов мы хотим наблюдать
        html:  'src/**/*.jade',
        js:    'src/js/**/*.js',
        style: 'src/style/**/**/*.*',
        img:   'src/img/**/*.*',
        fonts: 'src/fonts/**/*.*'
    },
    clean: './build'
};

var config = {
    server: {
        baseDir: "./build"
    },
    tunnel: true,
    host: 'localhost',
    port: 9000,
    logPrefix: "Front-End"
};


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

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

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

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

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

gulp.task('build', [
    'html:build',
    'js:build',
    'style:build'
]);

gulp.task('pre-build', [
    'fonts:build',
    'sprite',
    'image:build'
]);

gulp.task('watch', function(){
    watch([path.watch.html], function(event, cb) {
        gulp.start('html:build');
    });
    watch([path.watch.style], function(event, cb) {
        gulp.start('style: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('sprite', function() {
  var spriteData =
    gulp.src('./src/img/sprite/*.*') // путь, откуда берем картинки для спрайта
      .pipe(sprite({
        imgName: 'sprite.png',
        cssName: '5_sprite.css',
      }));

  spriteData.img.pipe(gulp.dest('./src/img/'));  // путь, куда сохраняем картинку
  spriteData.css.pipe(gulp.dest('./src/style/1_main-styles'));  // путь, куда сохраняем стили
});

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

Now, at the start of a new project, I write: npm i and I wait a long time along the way, looking at beautiful warnings in the console about the different packages that I use - something is outdated, etc.
Somewhere the other day I saw on a toaster in passing that they are currently using gulp 4, what is there are some goodies there that speed up the assembly, and the assembler is now not in one gulpfile, but is beautifully divided into several files and can be collected for development (pictures do not shrink there and something else does not shrink, unlike production) and separate assembly for production (presses everything to the maximum), but then I couldn’t find it on the toaster, and I didn’t google anything really except for the screencast from Ilya Kantor.
Tell me what to read / where to look to rewrite / write according to the new gulpfile, taking into account the new features of gulp without losing your good old convenient tasks. Or maybe someone will show a sensible workpiece?

Answer the question

In order to leave comments, you need to log in

5 answer(s)
D
Danila, 2016-05-07
@Machinez

Why didn't you like Kantor's screencast? considers galp 4 very deeply and intelligibly, you will not find better.
Read the documentation
Switching to galp 4 will not reduce the speed of installing modules and the number of warnings.
You can take something from my assembly , a lot is obtained from the screencast

_
_ _, 2016-05-07
@AMar4enko

Use webpack :D

I
itsjustmypage, 2016-05-09
@itsjustmypage

In order not to install packages every time, you can try to install all local packages globally (npm install <package> -g -D). All Gulp tasks can be divided into separate files, this is js.
You can make 2 types of assembly - for production and for yourself, in js through separate tasks.
Here is an example of such an assembly. alexfedoseev.com/post/54/frontend-project-build

S
sgrogov, 2016-05-10
@sgrogov

Check out the quick start template from csssr https://github.com/CSSSR/csssr-project-template. All tasks are written in es2015 syntax, caching is used to speed up assembly, tasks are divided into separate files, static data is rendered in json, svg is ready for use, there are retina sprites, BEM is used with might and main. There are many goodies, except that on windows there may be problems with installing dependencies (however, this is not a problem of the template itself, but of some modules in npm).

A
Artem Malko, 2016-07-07
@artemmalko

I recommend looking into how this is implemented in TARS!
You can learn how it all works from the report ( https://vimeo.com/123924728 20 minutes) or from the docks to TARS, everything is described in great detail there + there are articles on Habré .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question