As a backend developer, I often set up a sandbox application to quickly test new features in another context then the project I am working on. To facilitate this, I always use the same frontend setup, which I would like to share here. You can use this as a starting point for a full website, but for me it's just something that works and speeds up my development process. (Read: prevents me from wasting time on stuff I don't want to dive into.)
First, install gulp and a few related packages:
npm install node-sass gulp-sass gulp-concat gulp-clean-css gulp-minify --save-dev
Next up, creating a gulpfile:
var css_src = 'src/scss/*.scss',
js_src = 'src/js/*.js',
css_dest = 'dist/css/',
js_dest = 'dist/js/';
var gulp = require('gulp'),
gsass = require('gulp-sass'),
concat = require('gulp-concat'),
cleanCss = require('gulp-clean-css'),
minify = require('gulp-minify');
gulp.task('styles', function () {
return gulp.src(css_src)
.pipe(gsass().on('error', gsass.logError))
.pipe(cleanCss())
.pipe(concat('base.css'))
.pipe(gulp.dest(css_dest));
});
gulp.task('scripts', function() {
return gulp.src(js_src)
.pipe(minify({
ext:{
min:'.js'
},
noSource: true
}))
.pipe(concat('scripts.min.js'))
.pipe(gulp.dest(js_dest));
});
gulp.task('default', [], function () {
gulp.watch(js_src, ['scripts']);
gulp.watch(css_src, ['styles']);
});
A little explanation: we have a source directory for our Sass and one for our JavaScript code. Gulp will read files from these directories, parse, minify and concatenate those files and will create the optimized assets in the destiny directory.
To accomplish this we add two actions (styles
& scripts
) to the gulpfile, and set the default gulp task to watch the source directories. Whenever a file is saved to disk gulp will re-run those actions, updating our built files.
All we have to do now is include the base.css
and scripts.min.js
files in your application’s HTML, run gulp in the background (keep it running in another terminal) and you’re good to go!