Last active
January 25, 2018 03:22
-
-
Save neutraltone/fbd9e7bf5d64fc13b10c to your computer and use it in GitHub Desktop.
A gulp task for creating SVG sprites, loading them into your template with AJAX and styling them with CSS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Gulp Packages | |
* ============= | |
* Import our gulp packages. | |
*/ | |
import gulp from 'gulp'; | |
import svgmin from 'gulp-svgmin'; | |
import svgstore from 'gulp-svgstore'; | |
import cheerio from 'gulp-cheerio'; | |
/** | |
* Constants | |
* --------- | |
* Constants used throughout this boilerplate. | |
*/ | |
const pkg = require('./package.json'); | |
/** | |
* Directory Templates | |
* ------------------- | |
* Here we setup the various project directories | |
* making it easy to amend at a later date. | |
*/ | |
const project = { | |
src: 'src', | |
dist: 'dist' | |
}; | |
const iconPath = { | |
src: `${project.src}/icons/{,*/}*.svg`, | |
dest: `${project.dist}/assets/img` | |
} | |
/** | |
* SVG Sprite | |
* ---------- | |
* - Define prefix based on folder name | |
* - Sprite svg's | |
* - Copy sprite.svg to destination | |
*/ | |
gulp.task('svg-sprite', () => { | |
return gulp.src(spritePath.src) | |
.pipe(svgmin()) | |
.pipe(svgstore()) | |
.pipe(cheerio($ => $('svg').attr('style', 'display:none'))) | |
.pipe(gulp.dest(spritePath.dest)) | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.icon { | |
width: 1em; | |
height: 1em; | |
fill: currentColor; | |
&--facebook { | |
fill: #3b5998; | |
&:hover { | |
fill: #59983b; | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html lang="en"> | |
<head> | |
<script> | |
// Ajax SVG sprite. | |
window.addEventListener('load', function (event) { | |
var ajax = new XMLHttpRequest(); | |
ajax.open('GET', '/assets/img/sprite.svg', true); | |
ajax.send(); | |
ajax.onload = function (e) { | |
var div = document.createElement('div'); | |
div.innerHTML = ajax.responseText; | |
document.body.insertBefore(div, document.body.childNodes[0]); | |
} | |
}); | |
</script> | |
</head> | |
<body> | |
<svg class="icon icon--facebook"> | |
<use xlink:href="#icon-facebook" /> | |
</svg> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment