Advertisement
Guest User

Untitled

a guest
Jul 24th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // jshint ignore: start
  2. 'use strict';
  3. var gulp   = require('gulp'),
  4.     chalk  = require('chalk'),
  5.     plugin = require('gulp-load-plugins')(),
  6.     ssh    = require('gulp-ssh'),
  7.     fs     = require('fs');
  8. plugin.browserSync = require('browser-sync');
  9. plugin.rimraf = require('rimraf');
  10. plugin.vinylFtp = require('vinyl-ftp');
  11. plugin.imagemin.mozjpeg = require('imagemin-mozjpeg');
  12. plugin.imagemin.pngquant = require('imagemin-pngquant');
  13. plugin.imagemin.webp = require('imagemin-webp');
  14.  
  15. // Chalk colors: black red green yellow blue magenta cyan white gray redBright greenBright yellowBright blueBright magentaBright cyanBright whiteBright
  16.  
  17. fs.readFile('README.md', {encoding: 'utf-8', flag: 'rs'}, function(e, data) {
  18.     if (e) return console.log(e);
  19.     console.log(data);
  20. });
  21.  
  22. var path = {
  23.     build: {
  24.         html:  'build/',
  25.         php:   'build/',
  26.         js:    'build/js/',
  27.         css:   'build/',
  28.         img:   'build/images/',
  29.         fonts: 'build/fonts/',
  30.         maps:  'build/maps/',
  31.         svg:   'build/svg/',
  32.         media: 'build/media/',
  33.     },
  34.     src:   {
  35.         html:  'src/*.html',
  36.         php:   'src/**/*.php',
  37.         js:    'src/js/**/*.js',
  38.         css:   'src/**/*.scss',
  39.         img:   'src/images/**/*',
  40.         fonts: 'src/fonts/**/*.*',
  41.         svg:   'src/svg/**/*',
  42.         media: 'src/media/**/*.*',
  43.     },
  44.     watch: {
  45.         html:  'src/**/*.html',
  46.         php:   'src/**/*.php',
  47.         js:    'src/js/**/*.js',
  48.         css:   'src/**/*.scss',
  49.         img:   'src/images/**/*',
  50.         fonts: 'src/fonts/**/*.*',
  51.         svg:   'src/svg/**/*',
  52.         media: 'src/media/**/*.*',
  53.     },
  54.     clean:     './build',
  55.     update:    './package.json',
  56.     ftp:       '/',
  57. };
  58.  
  59. var enableFtp = false;
  60. var ftpconfig = JSON.parse(fs.readFileSync('.ftpconfig', 'utf-8'));
  61. var sshConnect = new ssh({
  62.     ignoreErrors: false,
  63.     sshConfig: {
  64.         host: ftpconfig.host,
  65.         port: ftpconfig.port,
  66.         username: ftpconfig.user,
  67.         password: ftpconfig.pass
  68.     }
  69. });
  70. path.ftp = ftpconfig.remote;
  71.  
  72. var browserSyncConfig = {
  73.     server:    {
  74.         baseDir: './build'
  75.     },
  76.     tunnel:    false,
  77.     host:      'localhost',
  78.     // proxy:     'localhost/project-placeholder/build/',
  79.     port:      9000,
  80.     logPrefix: 'Frontend'
  81. };
  82.  
  83. if(enableFtp) {
  84.     plugin.util.log(chalk.black.bgYellow('Загрузка на FTP активирована'));
  85. } else {
  86.     plugin.util.log(chalk.black.bgRed('Загрузка на FTP отключена'));
  87. }
  88.  
  89. gulp.task('webserver', function () {
  90.     plugin.browserSync(browserSyncConfig);
  91. });
  92.  
  93. gulp.task('html', function () {
  94.     gulp.src(path.src.html)
  95.         .pipe(plugin.changed(path.build.html))
  96.         .pipe(plugin.plumber({
  97.             errorHandler: plugin.notify.onError("Ошибка: <%= error.message %>")
  98.         })).on('end', function(){
  99.             plugin.util.log(chalk.red('Инициализирован обработчик ошибок HTML'));
  100.         })
  101.         .pipe(plugin.rigger()).on('end', function(){
  102.             plugin.util.log(chalk.red('Подключены внешние файлы HTML'));
  103.         })
  104.         .pipe(plugin.htmlmin({ // Описание настроек тут: https://github.com/kangax/html-minifier
  105.             collapseWhitespace: true,
  106.             minifyJS: true,
  107.             minifyCSS: true,
  108.             removeComments: true
  109.         })).on('end', function(){
  110.             plugin.util.log(chalk.red('Минифицирован HTML'));
  111.         })
  112.         .pipe(gulp.dest(path.build.html))
  113.         .on('end', function(){
  114.             plugin.util.log(chalk.bgRed('Файлы HTML скопированы в папку проекта'));
  115.         })
  116.         .pipe(plugin.browserSync.stream());
  117.     if(enableFtp){
  118.         gulp.src(path.build.html + '/*.html')
  119.             .pipe(sshConnect.dest(path.ftp))
  120.             .on('end', function(){ plugin.util.log(chalk.blue('HTML файлы загружены на SFTP')); });
  121.     }
  122. });
  123.  
  124. gulp.task('php', function() {
  125.     gulp.src(path.src.php)
  126.         .pipe(gulp.dest(path.build.php));
  127. });
  128.  
  129. gulp.task('js', function () {
  130.     gulp.src(path.src.js)
  131.         .pipe(plugin.changed(path.build.js))
  132.         .pipe(plugin.plumber({
  133.             errorHandler: plugin.notify.onError("Ошибка: <%= error.message %>")
  134.         })).on('end', function(){
  135.             plugin.util.log(chalk.yellow('Инициализирован обработчик ошибок JavaScript'));
  136.         })
  137.         .pipe(plugin.sourcemaps.init({
  138.             loadMaps: true
  139.         })).on('end', function(){
  140.             plugin.util.log(chalk.yellow('Инициализирован обработчик карт'));
  141.         })
  142.         .pipe(gulp.dest(path.build.js))
  143.         .pipe(plugin.browserSync.stream())
  144.         .on('end', function(){
  145.             plugin.util.log(chalk.black.bgYellow('Скрипты JavaScript скопированы в папку проекта'));
  146.         })
  147.         .pipe(plugin.rename({
  148.             suffix: '.min'
  149.         }))
  150.         .pipe(plugin.uglify())
  151.         .pipe(plugin.sourcemaps.write('../maps/'))
  152.         .pipe(gulp.dest(path.build.js))
  153.         .on('end', function(){
  154.             plugin.util.log(chalk.yellow('Созданы минифицированные версии скриптов JavaScript'));
  155.         })
  156.         .pipe(plugin.browserSync.stream());
  157.     if(enableFtp){
  158.         gulp.src(path.build.js + '/*.js')
  159.             .pipe(sshConnect.dest(path.ftp + '/js'))
  160.             .on('end', function(){ plugin.util.log(chalk.blue('Скрипты JavaScript загружены на SFTP')); });
  161.     }
  162. });
  163.  
  164. gulp.task('css', function () {
  165.     gulp.src(path.src.css)
  166.         .pipe(plugin.changed(path.build.css))
  167.         .pipe(plugin.plumber({
  168.             errorHandler: plugin.notify.onError("Ошибка: <%= error.message %>")
  169.         })).on('end', function(){
  170.             plugin.util.log(chalk.green('Инициализирован обработчик ошибок CSS'));
  171.         })
  172.         .pipe(plugin.versionNumber({'replaces':[[/#{VERSION_REPlACE}#/g,'%TS%']]}))
  173.         .on('end', function(){
  174.             plugin.util.log(chalk.green('Поставлена временная метка в поле версии'));
  175.         })
  176.         // .pipe(plugin.sourcemaps.init({
  177.         //  loadMaps: true
  178.         // })).on('end', function(){
  179.         //  plugin.util.log(chalk.green('Инициализирован обработчик карт'));
  180.         // })
  181.         .pipe(plugin.sass({
  182.             // sourcemap: true
  183.         })).on('end', function(){
  184.             plugin.util.log(chalk.green('Обработан SASS'));
  185.         })
  186.         .pipe(plugin.postcss([
  187.             require('postcss-gradientfixer')(),
  188.             require('postcss-flexbugs-fixes')(),
  189.             require('postcss-fixes')(),
  190.             require('postcss-flexibility')(),
  191.             require('postcss-color-rgba-fallback')(),
  192.             require('postcss-cssnext')({
  193.                 browsers: ['last 10 versions'],
  194.             }),
  195.         ])).on('end', function(){
  196.             plugin.util.log(chalk.green('Добавлены костыли для старых браузеров'));
  197.         })
  198.         .pipe(plugin.csscomb()).on('end', function(){
  199.             plugin.util.log(chalk.green('Скомбинированы стили'));
  200.         })
  201.         .pipe(plugin.mergeMediaQueries({
  202.             log: false
  203.         })).on('end', function(){
  204.             plugin.util.log(chalk.green('Скомпанованы @media'));
  205.         })
  206.         .pipe(plugin.webpcss()).on('end', function(){
  207.             plugin.util.log(chalk.green('Добавлены дополнительные классы для изображений webp'));
  208.         })
  209.         // .pipe(plugin.sourcemaps.write('./maps/')).on('end', function(){
  210.         //  plugin.util.log(chalk.green('Записаны карты для стилей'));
  211.         // })
  212.         .pipe(gulp.dest(path.build.css))
  213.         .on('end', function(){
  214.             plugin.util.log(chalk.bgGreen('Файлы CSS скопированы в папку проекта'));
  215.         })
  216.         .pipe(plugin.browserSync.stream())
  217.         .pipe(plugin.rename({
  218.             suffix: '.min'
  219.         }))
  220.         .pipe(plugin.cleanCss())
  221.         .pipe(plugin.sourcemaps.write('./maps/')).on('end', function(){
  222.             plugin.util.log(chalk.green('Записаны карты для минифицированных версий стилей'));
  223.         })
  224.         .pipe(gulp.dest(path.build.css))
  225.         .on('end', function(){
  226.             plugin.util.log(chalk.green('Добавлена минифицированная версия CSS'));
  227.         })
  228.         .pipe(plugin.browserSync.stream());
  229.     if(enableFtp){
  230.         gulp.src(path.build.css + '/*.css')
  231.             .pipe(sshConnect.dest(path.ftp))
  232.             .on('end', function(){ plugin.util.log(chalk.blue('Стили CSS загружены на SFTP')); });
  233.     }
  234. });
  235.  
  236. gulp.task('img', function () {
  237.     gulp.src(path.src.img)
  238.         .pipe(plugin.newer(path.build.img))
  239.         .pipe(plugin.plumber({
  240.             errorHandler: plugin.notify.onError("Ошибка: <%= error.message %>")
  241.         })).on('end', function(){
  242.             plugin.util.log(chalk.cyan('Инициализирован обработчик ошибок изображений'));
  243.         })
  244.         .pipe(plugin.imagemin([
  245.             plugin.imagemin.gifsicle({interlaced: true}),
  246.             plugin.imagemin.jpegtran({progressive: true}),
  247.             plugin.imagemin.mozjpeg({progressive: true}),
  248.             plugin.imagemin.optipng({optimizationLevel: 7}),
  249.             plugin.imagemin.pngquant({quality: '82-100'}),
  250.             plugin.imagemin.svgo({plugins: [{removeViewBox: true}]})
  251.         ]))
  252.         .pipe(gulp.dest(path.build.img))
  253.         .pipe(plugin.webp({
  254.             quality: 82,
  255.             alphaQuality: 100,
  256.             method: 6,
  257.             // lossless: true
  258.         }))
  259.         .pipe(gulp.dest(path.build.img))
  260.         .on('end', function(){ plugin.util.log(chalk.bgCyan('Изображения оптимизированы и скопированы в папку проекта')); })
  261.         .pipe(plugin.browserSync.stream());
  262.     if(enableFtp){
  263.         gulp.src(path.build.img + '**')
  264.             .pipe(sshConnect.dest(path.ftp + '/images'))
  265.             .on('end', function(){ plugin.util.log(chalk.blue('Изображения загружены на SFTP')); });
  266.     }
  267. });
  268.  
  269. gulp.task('fonts', function () {
  270.     gulp.src(path.src.fonts)
  271.         .pipe(gulp.dest(path.build.fonts))
  272.         .on('end', function(){
  273.             plugin.util.log(chalk.magenta('Шрифты скопированы в папку проекта'));
  274.         });
  275.     if(enableFtp){
  276.         gulp.src(path.build.fonts + '**')
  277.             .pipe(sshConnect.dest(path.ftp + '/fonts'))
  278.             .on('end', function(){ plugin.util.log(chalk.blue('Шрифты загружены на SFTP')); });
  279.     }
  280. });
  281.  
  282. gulp.task('media', function () {
  283.     gulp.src(path.src.media)
  284.         .pipe(gulp.dest(path.build.media))
  285.         .on('end', function(){
  286.             plugin.util.log(chalk.magenta('Медиафайлы скопированы в папку проекта'));
  287.         });
  288.     if(enableFtp){
  289.         gulp.src(path.build.media + '**')
  290.             .pipe(sshConnect.dest(path.ftp + '/media'))
  291.             .on('end', function(){ plugin.util.log(chalk.blue('Медиафайлы загружены на SFTP')); });
  292.     }
  293. });
  294.  
  295. gulp.task('svg', function () {
  296.     gulp.src(path.src.svg)
  297.         // .pipe(plugin.newer(path.build.svg))
  298.         // .pipe(plugin.svgmin())
  299.         // .on('end', function(){ plugin.util.log(chalk.magenta('Минифицированы векторные изображения')); })
  300.         .pipe(gulp.dest(path.build.svg))
  301.         .on('end', function(){ plugin.util.log(chalk.bgMagenta('Векторы SVG скопированы в папку проекта')); })
  302.         .pipe(plugin.browserSync.stream());
  303. });
  304.  
  305. gulp.task('watch', function () {
  306.     plugin.watch([path.watch.html], function (event, cb) {
  307.         gulp.start('html');
  308.     });
  309.  
  310.     plugin.watch([path.watch.php], function (event, cb) {
  311.         gulp.start('php');
  312.     });
  313.  
  314.     plugin.watch([path.watch.js], function (event, cb) {
  315.         gulp.start('js');
  316.     });
  317.  
  318.     plugin.watch([path.watch.css], function (event, cb) {
  319.         gulp.start('css');
  320.     });
  321.  
  322.     plugin.watch([path.watch.img], function (event, cb) {
  323.         gulp.start('img');
  324.     });
  325.  
  326.     plugin.watch([path.watch.svg], function (event, cb) {
  327.         gulp.start('svg');
  328.     });
  329.  
  330.     plugin.watch([path.watch.fonts], function (event, cb) {
  331.         gulp.start('fonts');
  332.     });
  333. });
  334.  
  335. gulp.task('watchjs', function () {
  336.     plugin.watch([path.watch.js], function (event, cb) {
  337.         gulp.start('js');
  338.     });
  339. });
  340.  
  341. gulp.task('clean', function (cb) {
  342.     plugin.rimraf(path.clean, cb);
  343. });
  344.  
  345. gulp.task('init', function () {
  346. });
  347.  
  348. gulp.task('default', [
  349.     'fonts',
  350.     'php',
  351.     'img',
  352.     'html',
  353.     'js',
  354.     'svg',
  355.     'css',
  356.     'webserver',
  357.     'watch'
  358. ]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement