Skip to content

Instantly share code, notes, and snippets.

@SvenPam
Created May 18, 2018 10:28
Show Gist options
  • Save SvenPam/7cf3feb4c87a9663808f09de8a2b2582 to your computer and use it in GitHub Desktop.
Save SvenPam/7cf3feb4c87a9663808f09de8a2b2582 to your computer and use it in GitHub Desktop.
Gulp Tasks
/// <binding ProjectOpened='watch' />
/******************************************************
* PATTERN LAB NODE
* EDITION-NODE-GULP
* The gulp wrapper around patternlab-node core, providing tasks to interact with the core library and move supporting frontend assets.
******************************************************/
const
fs = require('fs'),
gulp = require('gulp'),
path = require('path'),
browserSync = require('browser-sync').create(),
argv = require('minimist')(process.argv.slice(2)),
concat = require('gulp-concat'),
$ = require('gulp-load-plugins')({ lazy: true })
// Use fs to read config files we modify.
let
pkg = JSON.parse(fs.readFileSync('./package.json')),
config = JSON.parse(fs.readFileSync('./patternlab-config.json')),
paths = config.paths,
patternlab = require('patternlab-node')(config),
externalJs = require(paths.source.externalJs);
gulp.task('set-version', () => {
pkg.guideVersion = argv.projectversion == null ? 'Dev' : argv.projectversion;
return gulp.src([`package.json`, `${paths.source.data}/data.json`], { base: './' })
.pipe($.jsonEditor({
'guideVersion': pkg.guideVersion
}))
.pipe(gulp.dest('./'));
});
// -----------------------------------
// Scripts
// -----------------------------------
gulp.task('scripts:lint', function () {
return gulp.src('**/*.js', { cwd: paths.source.scripts })
.pipe($.jshint(pkg.jshintConfig))
.pipe($.jshint.reporter('default'))
.pipe($.jshint.reporter('fail'))
});
gulp.task('scripts:build', function () {
return gulp.src('**/*.js', { cwd: paths.source.scripts })
.pipe($.sourcemaps.init())
.pipe($.babel({
presets: ['es2015']
}))
.pipe(gulp.dest(paths.public.js))
.pipe($.uglify())
.pipe($.rename({ suffix: `.min` }))
.pipe(gulp.dest(paths.public.js))
.pipe($.rename({ suffix: `.${pkg.guideVersion}` }))
.pipe($.sourcemaps.write('.'))
.pipe(gulp.dest(paths.public.js))
});
gulp.task('scripts:external-build', function () {
return gulp.src(externalJs.references)
.pipe($.uglify())
.pipe(gulp.dest(paths.public.js));
});
gulp.task('scripts', gulp.series('scripts:lint', 'scripts:build'));
// -----------------------------------
// Styles
// -----------------------------------
gulp.task('styles:lint', function () {
return gulp.src(`${paths.source.styles}/**/*.s+(a|c)ss`)
.pipe($.sassLint(pkg.sassLintConfig))
.pipe($.sassLint.format())
.pipe($.sassLint.failOnError());
});
gulp.task('styles:build', function () {
return gulp.src(`${paths.source.styles}/*.scss`)
.pipe($.sourcemaps.init())
.pipe($.sass().on('error', $.sass.logError))
.pipe($.inlineBase64({
baseDir: `${paths.public.root}`,
maxSize: 14 * 1024 //14kb
}))
.pipe($.autoprefixer({
browsers: [
'Chrome >= 35',
'Firefox >= 38',
'Edge >= 12',
'Explorer >= 10',
'iOS >= 8',
'Safari >= 8',
'Android 2.3',
'Android >= 4',
'Opera >= 12'
]
}))
.pipe($.cssUrlencodeInlineSvgs()) // We need to ensure inline SVGs are encoded to work on FireFox
.pipe(gulp.dest(paths.public.styles))
.pipe($.cleanCss({ debug: true, semanticMerging: true }, function (details) {
console.log(`Original ${details.name}: ${details.stats.originalSize}`);
console.log(`Cleaned ${details.name}: ${details.stats.minifiedSize} (${Math.round((details.stats.minifiedSize / details.stats.originalSize) * 100)}%)`);
}))
.pipe(gulp.dest(paths.public.styles))
.pipe($.rename({ suffix: `.min` }))
.pipe(gulp.dest(paths.public.styles))
.pipe($.rename({ suffix: `.${pkg.guideVersion}` }))
.pipe($.sourcemaps.write('./'))
.pipe(gulp.dest(paths.public.styles))
.pipe(browserSync.stream());
});
gulp.task('styles', gulp.series('styles:lint', 'styles:build'/*, 'styles:external-build'*/));
// -----------------------------------
// Assets
// -----------------------------------
gulp.task('assets:sprites', function () {
return gulp.src(`${paths.source.images}/icon/**/*.svg`)
.pipe($.changed('./'))
.pipe($.svgSprite({
shape: {
spacing: {
padding: 2
}
},
svg: {
precision: 1
},
mode: {
css: {
example: true,
prefix: ".icon__%s",
dimensions: true,
render: {
scss: true
},
sprite: `./../../img/icons`
}
}
}))
.pipe($.imagemin())
.pipe(gulp.dest(`${paths.public.sprites}`));
});
gulp.task('assets:images', function () {
return gulp.src(`${paths.source.images}/**/*.*`)
.pipe($.changed('./'))
.pipe($.imagemin())
.pipe(gulp.dest(paths.public.images));
});
gulp.task('assets:font', function () {
return gulp.src(`${paths.source.fonts}/**/*.ttf`)
.pipe($.changed('./'))
.pipe($.fontmin({
text: "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz?&{|}\/~¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿĀāĂ㥹ĆćĈĉĊċČčĎďĐđĒēĔĕĖėĘęĚěĜĝĞğĠġĢģĤĥĦħĨĩĪīĬĭĮįİıIJijĴĵĶķĸĹĺĻļĽľĿŀŁłŃńŅņŇňʼnŊŋŌōŎŏŐőŒœŔŕŖŗŘřŚśŜŝŞşŠšŢţŤťŦŧŨũŪūŬŭŮůŰűŲųŴŵŶŷŸŹźŻżŽž,“”‘’", //Basic Latin & Latin Extended
hinting: false,
quiet: false
}))
.pipe($.ttf2woff2())
.pipe(gulp.dest(paths.public.fonts));
});
gulp.task('assets:favicon', function () {
return gulp.src(`${paths.source.root}/favicon.ico`)
.pipe(gulp.dest(paths.public.root));
});
gulp.task('assets:config', function () {
return gulp.src(`${paths.source.root}/Web.config`)
.pipe($.changed('./'))
.pipe(gulp.dest(paths.public.root));
});
// Images must be completed before styles due to sprite & inline dependencies.
gulp.task('assets', gulp.series(
gulp.parallel(
'scripts:build',
'scripts:external-build',
'assets:font',
'assets:sprites',
'assets:images',
'assets:favicon',
'assets:config'
),
'styles',
function (done) {
done();
})
);
// -----------------------------------
// PatternLab
// -----------------------------------
function getConfiguredCleanOption() {
return config.cleanPublic;
}
function build(done) {
patternlab.build(done, getConfiguredCleanOption());
}
gulp.task('patternlab:styleguide-css', function () {
return gulp.src(paths.source.styleguide + '/**/*.css')
.pipe(gulp.dest(function (file) {
//flatten anything inside the styleguide into a single output dir per http://stackoverflow.com/a/34317320/1790362
file.path = path.join(file.base, path.basename(file.path));
return path.join(paths.public.styleguide, '/css');
}))
.pipe(browserSync.stream());
});
gulp.task('patternlab:styleguide', function () {
return gulp.src(paths.source.styleguide + '/**/!(*.css)')
.pipe(gulp.dest(paths.public.root))
.pipe(browserSync.stream());
});
gulp.task('patternlab:patternsonly', function (done) {
patternlab.patternsonly(done, getConfiguredCleanOption());
});
gulp.task('patternlab:build', gulp.parallel('assets', 'patternlab:styleguide', 'patternlab:styleguide-css', build, function (done) {
done();
}));
/******************************************************
* SERVER AND WATCH TASKS
******************************************************/
// watch task utility functions
function getSupportedTemplateExtensions() {
var engines = require('./node_modules/patternlab-node/core/lib/pattern_engines');
return engines.getSupportedFileExtensions();
}
function getTemplateWatches() {
return getSupportedTemplateExtensions().map(function (dotExtension) {
return paths.source.patterns + '/**/*' + dotExtension;
});
}
function reload() {
browserSync.reload();
}
function reloadCSS() {
browserSync.reload('*.css');
}
function watch() {
gulp.watch(`${paths.source.styles}/**/*.scss`, { awaitWriteFinish: true }).on('change', gulp.series('styles', reloadCSS));
gulp.watch(`${paths.source.scripts}/**/*.js`, { awaitWriteFinish: true }).on('change', gulp.series('scripts', reload));
gulp.watch(`${paths.source.images}/**/*`, { awaitWriteFinish: true }).on('change', gulp.series('assets:images', 'assets:sprites', 'styles', reload));
gulp.watch(`${paths.source.fonts}/**/*.ttf`, { awaitWriteFinish: true }).on('change', gulp.series('assets:font', reload));
var patternWatches = [
paths.source.patterns + '/**/*.json',
paths.source.patterns + '/**/*.md',
paths.source.data + '/*.json',
paths.source.meta + '/*',
paths.source.annotations + '/*',
externalJs.references
].concat(getTemplateWatches());
gulp.watch(patternWatches, { awaitWriteFinish: true }).on('change', gulp.series(build, reload));
}
gulp.task('patternlab:connect', gulp.series(function (done) {
browserSync.init({
server: {
baseDir: paths.public.root
},
snippetOptions: {
// Ignore all HTML files within the templates folder
blacklist: ['/index.html', '/', '/?*']
},
notify: {
styles: [
'display: none',
'padding: 15px',
'font-family: sans-serif',
'position: fixed',
'font-size: 1em',
'z-index: 9999',
'bottom: 0px',
'right: 0px',
'border-top-left-radius: 5px',
'background-color: #1B2032',
'opacity: 0.4',
'margin: 0',
'color: white',
'text-align: center'
]
}
}, function () {
console.log('PATTERN LAB NODE WATCHING FOR CHANGES');
done();
});
}));
/******************************************************
* COMPOUND TASKS
******************************************************/
gulp.task('default', gulp.series('set-version', 'patternlab:build'));
gulp.task('patternlab:watch', gulp.series('patternlab:build', watch));
gulp.task('patternlab:serve', gulp.series('patternlab:build', 'patternlab:connect', watch));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment