Skip to content

Instantly share code, notes, and snippets.

@AntonLitvin
Last active May 22, 2018 08:56
Show Gist options
  • Save AntonLitvin/b7d79d224e75f128492a23c9ce57c26f to your computer and use it in GitHub Desktop.
Save AntonLitvin/b7d79d224e75f128492a23c9ce57c26f to your computer and use it in GitHub Desktop.
by html academy
//My gulpfile based on htmlacademy
package.json
{
"name": "project",
"version": "1.0.0",
"private": true,
"description": "",
"author": "Anton Litvinenko",
"devDependencies": {
"autoprefixer": "^7.1.1",
"browser-sync": "^2.18.12",
"css-mqpacker": "^6.0.1",
"del": "^3.0.0",
"gulp": "^3.9.1",
"gulp-cheerio": "^0.6.2",
"gulp-concat": "^2.6.1",
"gulp-csso": "^3.0.0",
"gulp-imagemin": "^3.3.0",
"gulp-notify": "^3.0.0",
"gulp-plumber": "^1.1.0",
"gulp-postcss": "^7.0.0",
"gulp-rename": "^1.2.2",
"gulp-sass": "^3.1.0",
"gulp-svgmin": "^1.2.4",
"gulp-svgstore": "^6.1.0",
"gulp-uglify": "^3.0.0",
"imagemin-pngquant": "^5.0.1",
"run-sequence": "^2.0.0"
}
}
gulpfile.js
'use strict';
var gulp = require('gulp'),
sass = require('gulp-sass'),
plumber = require('gulp-plumber'),//отлавливает ошибки, не дает упасть серверу
browserSync = require('browser-sync').create(),
postcss = require('gulp-postcss'),//нужен для работы автопрефиксера
autoprefixer = require('autoprefixer'),//работает под postcss
mqpacker = require('css-mqpacker'),//перераспределятор медиавыражений, работает под postcss
csso = require('gulp-csso'),//минификатор CSS
rename = require('gulp-rename'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
notify = require('gulp-notify'),
svgstore = require('gulp-svgstore'),//собиральщик спрайта
svgmin = require('gulp-svgmin'),//минификатор SVG
imagemin = require('gulp-imagemin'),
pngquant = require('imagemin-pngquant'),
cheerio = require('gulp-cheerio'),
run = require('run-sequence'),//запуск тасков последовательно
// ghPages = require('gulp-gh-pages'),
del = require('del');
// Сборка стилей
gulp.task('style', function() {
gulp.src('app/sass/main.scss')
.pipe(plumber())
.pipe(sass({outputStyle: 'expand'})).on('error', notify.onError())
.pipe(postcss([
autoprefixer({browsers: [
'last 10 versions'
]}),
mqpacker({
sort: false //true сортирует медиастили по порядку
})
]))
.pipe(gulp.dest('app/css'))//несжатый CSS
.pipe(csso())//сжимает CSS
.pipe(rename('style.min.css'))
.pipe(gulp.dest('app/css'))//сжатый CSS
.pipe(browserSync.reload({stream: true}));
});
// Сборка скриптов
gulp.task('common-js', function() {
return gulp.src([
'app/js/common.js',
])
.pipe(plumber())
.pipe(concat('common.min.js'))
.pipe(uglify().on('error', notify.onError()))
.pipe(gulp.dest('app/js'));
});
gulp.task('js', ['common-js'], function() {
return gulp.src([
'app/libs/jquery/dist/jquery.min.js', // сюда добавляем библиотеки
//'app/js/common.min.js', // Всегда в конце, раскоментить, если хотим склеить весь js, удалить подключение common.js в index.html
])
.pipe(plumber())
.pipe(concat('scripts.min.js'))
.pipe(uglify()) // Минимизировать весь js (на выбор)
.pipe(gulp.dest('app/js'))
.pipe(browserSync.reload({stream: true}));
});
// Оптимизация изображений
gulp.task('img', function () {
return gulp.src('app/img/**/*')
.pipe(plumber())
.pipe(imagemin({
optimizationLevel: 3,
progressive: true,
svgoPlugins: [{removeViewBox: false}],
use: [pngquant()]
}))
.pipe(gulp.dest('build/img'));
});
// Сборка SVG-спрайта
gulp.task('svgstore', function (callback) {
var spritePath = 'app/img/svg-sprite';
if(fileExist(spritePath) !== false) {
return gulp.src(spritePath + '/*.svg')
.pipe(svgmin(function (file) {
return {
plugins: [{
cleanupIDs: {
minify: true
}
}]
};
}))
.pipe(svgstore({ inlineSvg: true }))
.pipe(cheerio(function ($) {
$('svg').attr('style', 'display:none');
}))
.pipe(rename('sprite-svg.svg'))
.pipe(gulp.dest('build/img/'));
}
else {
console.log('Нет файлов для сборки SVG-спрайта');
callback();
}
});
// Копирование шрифтов, скриптов, SVG-спрайтов и html
gulp.task('copy', function() {
return gulp.src([
'app/fonts/**/*.*',
'app/js/scripts.min.js',
'app/js/common.js',
'app/css/style.min.css',
'app/*.html'
], {
base: 'app'
})
.pipe(gulp.dest('build'));
});
// Очистка папки build
gulp.task('clean', function() {
return del('build');
});
// Сборка проекта в папку build
gulp.task('build', function(fn) {
run(
'clean',
'style',
'img',
'svgstore',
'copy',
fn
);
});
// Слежение за изменениями, локальный сервер
gulp.task('serve', ['style'], function() {
browserSync.init({
server: 'app',
notify: false,
open: true,
tunnel: false,
cors: true,
ui: false
});
gulp.watch('app/sass/**/*.{scss,sass}', ['style']);
gulp.watch(['libs/**/*.js', 'app/js/common.js'], ['js']);
gulp.watch('app/*.html', browserSync.reload);
});
// Задача по умолчанию
gulp.task('default', ['serve']);
// Проверка существования файла/папки
function fileExist(path) {
var fs = require('fs');
try {
fs.statSync(path);
} catch(err) {
return !(err && err.code === 'ENOENT');
}
}
// gulp.task('deploy', function() {
// return gulp.src('./build/**/*')
// .pipe(ghPages());
// });
/////////////////////////////////////////////////////////////////////////////////////////////////////
//Original htmlacademy gulpfile
package.json
{
"name": "project",
"version": "1.0.0",
"private": true,
"description": "Some Project",
"author": "Anton Litvinenko",
"devDependencies": {
"@htmlacademy/editorconfig-cli": "0.1.x",// нужно удалить
"autoprefixer": "6.7.x",
"browser-sync": "~2.18.8",
"css-mqpacker": "^5.0.1",
"del": "^2.2.2",
"gulp": "~3.9.1",
"gulp-cheerio": "^0.6.2",
"gulp-csso": "^3.0.0",
"gulp-imagemin": "^3.2.0",
"gulp-plumber": "~1.1.0",
"gulp-postcss": "~6.2.0",
"gulp-rename": "^1.2.2",
"gulp-sass": "~3.1.0",
"gulp-svgmin": "^1.2.3",
"gulp-svgstore": "^6.1.0",
"imagemin-pngquant": "^5.0.0",
"run-sequence": "^1.2.2"
},
"scripts": {
"test": "editorconfig-cli",// нужно удалить
"build": "npm start build",
"start": "gulp"
},
"editorconfig-cli": [
"*.html",
"*.json",
"*.js",
"js/**/*.js",
"img/**/*.svg",
"sass/**/*.{sass,scss}"
]
//,
// "engines": {
// "node": "6.10"
//}
}
gulpfile.js
"use strict";
var gulp = require("gulp"),
sass = require("gulp-sass"),
plumber = require("gulp-plumber"),//отлавливает ошибки, не дает упасть серверу
browserSync = require("browser-sync").create(),
postcss = require("gulp-postcss"),//нужен для работы автопрефиксера
autoprefixer = require("autoprefixer"),//работает под postcss
mqpacker = require("css-mqpacker"),//перераспределятор медиавыражений, работает под postcss
csso = require("gulp-csso"),//минификатор CSS
rename = require("gulp-rename"),
svgstore = require("gulp-svgstore"),//собиральщик спрайта
svgmin = require("gulp-svgmin"),//минификатор SVG
imagemin = require("gulp-imagemin"),
pngquant = require("imagemin-pngquant"),
cheerio = require("gulp-cheerio"),
ghPages = require('gulp-gh-pages'),
run = require("run-sequence"),//запуск тасков последовательно
del = require("del");
// ЗАДАЧА: Сборка стилей
gulp.task("style", function() {
gulp.src("sass/style.scss")
.pipe(plumber())
.pipe(sass())
.pipe(postcss([
autoprefixer({browsers: [
"last 2 versions"
]}),
mqpacker({
sort: false //true сортирует медиастили по порядку
})
]))
.pipe(gulp.dest("build/css"))//несжатый CSS
.pipe(browserSync.stream())
.pipe(csso())//сжимает CSS
.pipe(rename("style.min.css"))
.pipe(gulp.dest("build/css"));//сжатый CSS
});
// ЗАДАЧА: Копирование изображений
gulp.task("img", function () {
return gulp.src("img/*.{gif,png,jpg,jpeg,svg}")
.pipe(plumber())
.pipe(imagemin({
optimizationLevel: 3,
progressive: true,
svgoPlugins: [{removeViewBox: false}],
use: [pngquant()]
}))
.pipe(gulp.dest("build/img"));
});
// ЗАДАЧА: Сборка SVG-спрайта
gulp.task("svgstore", function (callback) {
var spritePath = "img/svg-sprite";
if(fileExist(spritePath) !== false) {
return gulp.src(spritePath + "/*.svg")
.pipe(svgmin(function (file) {
return {
plugins: [{
cleanupIDs: {
minify: true
}
}]
};
}))
.pipe(svgstore({ inlineSvg: true }))
.pipe(cheerio(function ($) {
$("svg").attr("style", "display:none");
}))
.pipe(rename("sprite-svg.svg"))
.pipe(gulp.dest("build/img/"));
}
else {
console.log("Нет файлов для сборки SVG-спрайта");
callback();
}
});
// ЗАДАЧА: Копирование шрифтов, скриптов и html
gulp.task("copy", function() {
return gulp.src([
"fonts/**/*.{woff,woff2}",
"js/**",
"*.html"
], {
base: "."
})
.pipe(gulp.dest("build"));
});
gulp.task("clean", function() {
return del("build");
});
gulp.task("build", function(fn) {
run(
"clean",
"copy",
"style",
"img",
"svgstore",
fn
);
});
gulp.task("html:copy", function() {
return gulp.src("*.html")
.pipe(gulp.dest("build"));
});
gulp.task("html:update", ["html:copy"], function(done) {
browserSync.reload();
done();
});
gulp.task("serve", ["style"], function() {
browserSync.init({
server: "build",
notify: false,
open: true,
cors: true,
ui: false
});
gulp.watch("sass/**/*.{scss,sass}", ["style"]);
gulp.watch("*.html", ["html:update"]);
});
gulp.task('deploy', function() {
return gulp.src('./build/**/*')
.pipe(ghPages());
});
// ЗАДАЧА: Задача по умолчанию
gulp.task("default", ["serve"]);
// Проверка существования файла/папки
function fileExist(path) {
const fs = require("fs");
try {
fs.statSync(path);
} catch(err) {
return !(err && err.code === "ENOENT");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment