Commit 85725763 authored by Nikolay Gromov's avatar Nikolay Gromov

Разобрался со спрайтами

parent 2b21ff0b
...@@ -147,16 +147,15 @@ gulp.task('copy:fonts', function () { ...@@ -147,16 +147,15 @@ gulp.task('copy:fonts', function () {
}); });
// Сборка SVG-спрайта для блока sprite-svg // Сборка SVG-спрайта для блока sprite-svg
let spritePath = dirs.srcPath + dirs.blocksDirName + '/sprite-svg/svg/'; let spriteSvgPath = dirs.srcPath + dirs.blocksDirName + '/sprite-svg/svg/';
gulp.task('sprite:svg', function (callback) { gulp.task('sprite:svg', function (callback) {
if((pjson.configProject.blocks['sprite-svg']) !== undefined) { if((pjson.configProject.blocks['sprite-svg']) !== undefined) {
const svgstore = require('gulp-svgstore'); const svgstore = require('gulp-svgstore');
const svgmin = require('gulp-svgmin'); const svgmin = require('gulp-svgmin');
const cheerio = require('gulp-cheerio'); const cheerio = require('gulp-cheerio');
let spritePath = dirs.srcPath + dirs.blocksDirName + '/sprite-svg/svg/'; if(fileExist(spriteSvgPath) !== false) {
if(fileExist(spritePath) !== false) {
console.log('---------- Сборка SVG спрайта'); console.log('---------- Сборка SVG спрайта');
return gulp.src(spritePath + '*.svg') return gulp.src(spriteSvgPath + '*.svg')
.pipe(svgmin(function (file) { .pipe(svgmin(function (file) {
return { return {
plugins: [{ plugins: [{
...@@ -189,6 +188,46 @@ gulp.task('sprite:svg', function (callback) { ...@@ -189,6 +188,46 @@ gulp.task('sprite:svg', function (callback) {
} }
}); });
// Сборка SVG-спрайта для блока sprite-png
let spritePngPath = dirs.srcPath + dirs.blocksDirName + '/sprite-png/png/';
gulp.task('sprite:png', function () {
if((pjson.configProject.blocks['sprite-png']) !== undefined) {
const spritesmith = require('gulp.spritesmith');
const buffer = require('vinyl-buffer');
const merge = require('merge-stream');
const imagemin = require('gulp-imagemin');
const pngquant = require('imagemin-pngquant');
if(fileExist(spritePngPath) !== false) {
del(dirs.srcPath + dirs.blocksDirName + '/sprite-png/img/*.png');
let fileName = 'sprite-' + Math.random().toString().replace(/[^0-9]/g, '') + '.png';
let spriteData = gulp.src(spritePngPath + '*.png')
.pipe(spritesmith({
imgName: fileName,
cssName: 'sprite-png.scss',
padding: 4,
imgPath: '../img/' + fileName
}));
let imgStream = spriteData.img
.pipe(buffer())
.pipe(imagemin({
use: [pngquant()]
}))
.pipe(gulp.dest(dirs.srcPath + dirs.blocksDirName + '/sprite-png/img/'));
let cssStream = spriteData.css
.pipe(gulp.dest(dirs.srcPath + dirs.blocksDirName + '/sprite-png/'));
return merge(imgStream, cssStream);
}
else {
console.log('---------- Сборка PNG спрайта: ОТМЕНА, нет папки с картинками');
callback();
}
}
else {
console.log('---------- Сборка PNG спрайта: ОТМЕНА, блок не используется на проекте');
callback();
}
});
// Сборка HTML // Сборка HTML
gulp.task('html', function() { gulp.task('html', function() {
const fileinclude = require('gulp-file-include'); const fileinclude = require('gulp-file-include');
...@@ -261,7 +300,7 @@ gulp.task('img:opt', function (callback) { ...@@ -261,7 +300,7 @@ gulp.task('img:opt', function (callback) {
gulp.task('build', function (callback) { gulp.task('build', function (callback) {
gulpSequence( gulpSequence(
'clean', 'clean',
'sprite:svg', ['sprite:svg', 'sprite:png'],
['style', 'js', 'copy:css', 'copy:img', 'copy:js', 'copy:fonts'], ['style', 'js', 'copy:css', 'copy:img', 'copy:js', 'copy:fonts'],
'html', 'html',
callback callback
...@@ -304,11 +343,7 @@ gulp.task('serve', ['build'], function() { ...@@ -304,11 +343,7 @@ gulp.task('serve', ['build'], function() {
gulp.watch(pjson.configProject.copiedJs, ['watch:copied:js']); gulp.watch(pjson.configProject.copiedJs, ['watch:copied:js']);
} }
// Слежение за шрифтами // Слежение за шрифтами
gulp.watch(dirs.srcPath + '/fonts/*.{ttf,woff,woff2,eot,svg}', ['watch:fonts']); gulp.watch('/fonts/*.{ttf,woff,woff2,eot,svg}', {cwd: dirs.srcPath}, ['watch:fonts']);
// Слежение за SVG для спрайта
if(fileExist(spritePath) !== false) {
gulp.watch(spritePath + '*.svg', ['watch:svg:sprite']);
}
// Слежение за html // Слежение за html
gulp.watch([ gulp.watch([
dirs.srcPath + '/*.html', dirs.srcPath + '/*.html',
...@@ -319,15 +354,24 @@ gulp.task('serve', ['build'], function() { ...@@ -319,15 +354,24 @@ gulp.task('serve', ['build'], function() {
if(lists.js.length) { if(lists.js.length) {
gulp.watch(lists.js, ['watch:js']); gulp.watch(lists.js, ['watch:js']);
} }
// Слежение за SVG (спрайты)
if((pjson.configProject.blocks['sprite-svg']) !== undefined) {
gulp.watch('*.svg', {cwd: spriteSvgPath}, ['watch:sprite:svg']); // следит за новыми и удаляемыми файлами
}
// Слежение за PNG (спрайты)
if((pjson.configProject.blocks['sprite-png']) !== undefined) {
gulp.watch('*.png', {cwd: spritePngPath}, ['watch:sprite:png']); // следит за новыми и удаляемыми файлами
}
}); });
// Браузерсинк с 3-м галпом — такой браузерсинк... // Браузерсинк с 3-м галпом — такой браузерсинк...
gulp.task('watch:img', ['copy:img'], reload); gulp.task('watch:img', ['copy:img'], reload);
gulp.task('watch:copied:js', ['copy:js'], reload); gulp.task('watch:copied:js', ['copy:js'], reload);
gulp.task('watch:fonts', ['copy:fonts'], reload); gulp.task('watch:fonts', ['copy:fonts'], reload);
gulp.task('watch:svg:sprite', ['sprite:svg'], reload);
gulp.task('watch:html', ['html'], reload); gulp.task('watch:html', ['html'], reload);
gulp.task('watch:js', ['js'], reload); gulp.task('watch:js', ['js'], reload);
gulp.task('watch:sprite:svg', ['sprite:svg'], reload);
gulp.task('watch:sprite:png', ['sprite:png'], reload);
......
...@@ -11,7 +11,8 @@ ...@@ -11,7 +11,8 @@
"configProject": { "configProject": {
"blocks": { "blocks": {
"page-header": [], "page-header": [],
"page-footer": [] "page-footer": [],
"sprite-svg": []
}, },
"addCssBefore": [ "addCssBefore": [
"./src/scss/variables.scss" "./src/scss/variables.scss"
...@@ -21,7 +22,8 @@ ...@@ -21,7 +22,8 @@
], ],
"addJsBefore": [ "addJsBefore": [
"./node_modules/jquery/dist/jquery.min.js", "./node_modules/jquery/dist/jquery.min.js",
"./node_modules/jquery-migrate/dist/jquery-migrate.min.js" "./node_modules/jquery-migrate/dist/jquery-migrate.min.js",
"./node_modules/svg4everybody/dist/svg4everybody.js"
], ],
"addJsAfter": [ "addJsAfter": [
"./src/js/global-script.js" "./src/js/global-script.js"
...@@ -72,8 +74,12 @@ ...@@ -72,8 +74,12 @@
"gulp-svgmin": "^1.2.3", "gulp-svgmin": "^1.2.3",
"gulp-svgstore": "^6.1.0", "gulp-svgstore": "^6.1.0",
"gulp-uglify": "^2.1.0", "gulp-uglify": "^2.1.0",
"gulp.spritesmith": "^6.3.0",
"imagemin-pngquant": "^5.0.0", "imagemin-pngquant": "^5.0.0",
"jquery": "^3.1.1", "jquery": "^3.1.1",
"jquery-migrate": "^3.0.0" "jquery-migrate": "^3.0.0",
"merge-stream": "^1.0.1",
"svg4everybody": "^2.1.7",
"vinyl-buffer": "^1.0.0"
} }
} }
Папка, в кторую генерируется спрайт.
# PNG-спрайт
**ВНИМАНИЕ!** Имена файлов для спрайта не должны начинаться с цифры! Из имен формируются переменные, которые не могут начинаться с цифр.
Из файлов папки `png/` в папку `img/` будет сгенерирован файл спрайта `sprite-УНИКАЛЬНЫЙЦИФРОВОЙИНДЕКС.png`.
В `sprite-png.scss` будет сгенерирован набор переменных и примесей для использования спрайта.
# SVG-спрайт с использованием символов # SVG-спрайт с использованием символов
**ВНИМАНИЕ!** Чтобы использовать ссылки на внешние svg-файлы со спрайтами, используйте [svg4everybody](https://www.npmjs.com/package/svg4everybody).
Из файлов папки `svg/` в папку `img/` будет сгенерирован файл спрайта `sprite-svg.svg`. Из файлов папки `svg/` в папку `img/` будет сгенерирован файл спрайта `sprite-svg.svg`.
Сам спрайт имеет вид: Сам спрайт имеет вид:
```svg ```html
<svg xmlns="http://www.w3.org/2000/svg" style="display:none"> <svg xmlns="http://www.w3.org/2000/svg" style="display:none">
<symbol id="icon-1" viewBox="0 0 30 30"><path fill="#444" d="..."/></symbol> <symbol id="icon-1" viewBox="0 0 30 30"><path fill="#444" d="..."/></symbol>
<symbol id="icon-2" viewBox="0 0 28 28"><path fill="#444" d="..."/></symbol> <symbol id="icon-2" viewBox="0 0 28 28"><path fill="#444" d="..."/></symbol>
...@@ -14,5 +16,5 @@ ...@@ -14,5 +16,5 @@
Для вставки на страницу используйте конструкции `svg > use` со ссылками на `id` символа: Для вставки на страницу используйте конструкции `svg > use` со ссылками на `id` символа:
```html ```html
<svg width="30" height="30"><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#icon-1"></use></svg> <svg width="30" height="30"><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="img/sprite-svg.svg#temp-icon-right-arrow"></use></svg>
``` ```
...@@ -2,6 +2,8 @@ ...@@ -2,6 +2,8 @@
Это пример использования спрайта: Это пример использования спрайта:
<svg width="30" height="30"><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#icon-1"></use></svg> <svg width="30" height="30"><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="img/sprite-svg.svg#temp-icon-right-arrow"></use></svg>
Для поддержки IE используйте svg4everybody — https://www.npmjs.com/package/svg4everybody
--> -->
;( function( window, document ) { svg4everybody();
'use strict';
var file = 'img/sprite-svg--ls.svg', // URL файла относительно страницы, на которой он используется (можно — абсолютный)
revision = 1; // Номер ревизии (сменить при обновлении спрайта)
if( !document.createElementNS || !document.createElementNS( 'http://www.w3.org/2000/svg', 'svg' ).createSVGRect ) {
return true;
}
var isLocalStorage = 'localStorage' in window && window[ 'localStorage' ] !== null,
request,
data,
insertIT = function() {
document.body.insertAdjacentHTML( 'afterbegin', data );
},
insert = function() {
if( document.body ) insertIT();
else document.addEventListener( 'DOMContentLoaded', insertIT );
};
if( isLocalStorage && localStorage.getItem( 'inlineSVGrev' ) == revision ) {
data = localStorage.getItem( 'inlineSVGdata' );
if( data ) {
insert();
return true;
}
}
try {
request = new XMLHttpRequest();
request.open( 'GET', file, true );
request.onload = function()
{
if( request.status >= 200 && request.status < 400 ) {
data = request.responseText;
insert();
if( isLocalStorage ) {
localStorage.setItem( 'inlineSVGdata', data );
localStorage.setItem( 'inlineSVGrev', revision );
}
}
}
request.send();
}
catch( e ){}
}( window, document ) );
...@@ -12,6 +12,8 @@ ...@@ -12,6 +12,8 @@
<h1>NTH start project</h1> <h1>NTH start project</h1>
<svg width="30" height="30"><use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="img/sprite-svg.svg#temp-icon-right-arrow"></use></svg>
<p><img src="img/joker.jpg" alt="" width="824" height="460"></p> <p><img src="img/joker.jpg" alt="" width="824" height="460"></p>
<input type="text" value ="qwerty"> <input type="text" value ="qwerty">
......
...@@ -7,4 +7,6 @@ ...@@ -7,4 +7,6 @@
@import "./src/scss/variables.scss"; @import "./src/scss/variables.scss";
@import "./src/blocks/page-header/page-header.scss"; @import "./src/blocks/page-header/page-header.scss";
@import "./src/blocks/page-footer/page-footer.scss"; @import "./src/blocks/page-footer/page-footer.scss";
@import "./src/blocks/sprite-svg/sprite-svg.scss";
@import "./src/blocks/sprite-png/sprite-png.scss";
@import "./src/scss/print.scss"; @import "./src/scss/print.scss";
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment