Understanding Gulp sass compilation - node.js

I have a gulpfile.js with some tasks to compile client side coffeescript and my styles which are in sass. The coffeescript is compiling correctly, but sass is not.
Here is my gulpfile.js -
var gulp = require('gulp'),
util = require('gulp-util'),
sass = require('gulp-sass'),
coffee = require('gulp-coffee');
var paths = {
scripts: {
src: 'src/coffee/**/*.coffee',
dest: 'public/javascripts'
},
styles: {
src: 'src/*.sass',
dest: 'public/stylesheets'
}
};
gulp.task('scripts', function() {
return gulp.src(paths.scripts.src)
.pipe(coffee())
.pipe(gulp.dest(paths.scripts.dest));
});
gulp.task('sass', function () {
return gulp.src(paths.styles.src)
.pipe(sass({errLogToConsole: true}))
.pipe(gulp.dest(paths.styles.dest));
});
gulp.task('watch', function () {
gulp.watch(paths.scripts.src, ['scripts']);
gulp.watch(paths.styles.src, ['styles']);
});
gulp.task('default', ['scripts', 'watch']);
It's got to be in my 'watch' task, but what is it missing?
* EDIT *
Here is the output I am getting -
[gulp] Using file exampledir/gulpfile.js
[gulp] Working directory changed to exampledir/examplesite
[gulp] Running 'scripts'...
[gulp] Running 'watch'...
[gulp] Finished 'watch' in 14 ms
[gulp] Finished 'scripts' in 106 ms
[gulp] Running 'default'...
[gulp] Finished 'default' in 10 μs

It seems that you forgot the .src oth your gulp.src(path.styles).
It bet it will work better :)
gulp.task('sass', function () {
return gulp.src(paths.styles.src)
.pipe(sass({errLogToConsole: true}))
.pipe(gulp.dest(paths.styles.dest));
});
* EDIT *
Other point: the default task does not depends on the saas task. That's why it's not executed.
gulp.task('default', ['scripts', 'sass', 'watch']);
will fix it.
Otherwise, watch just wait for one of your style files to be modified before compiling it.
It does not trigger the compilation when starting.
* EDIT v2 *
If you which to compile both .scss and .sass extension, just adapt your path.styles.src variable.
paths = {
...
styles: {
src: ['src/*.scss', 'src/*.sass']
...
Should work. Unless it's the way vinyl-fs seems to work.
* EDIT v3 *
Damn.
The watch on styles folder isn't correct. It triggers a undeinfed styles task.
try changing it to sass task.
gulp.watch(paths.styles.src, ['sass']);

After spend a long time trying to use the gulp-sass to compile my .sass files I decided to use the compass plugin instead. Works like a charm:
gulp.task('sass', function() {
return gulp.src('./src/sass/' + '**/*.sass')
.pipe($plugin.plumber())
.pipe($plugin.compass({
css: './public/css',
sass: './src/sass/'
}))
.pipe(gulp.dest('./public/css'));
});

Related

Node.js Gulp no outputfile created

I have a Gulp script to concatenate, and minimize javascript.
It seems to be working but doesn't output the combined file.
The script is (complete - including extra debug bits):
// include plug-ins
var fs = require('fs');
var gulp = require('gulp');
var count = require('gulp-count');
var debug = require('gulp-debug');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var del = require('del');
var config = {
src: 'dist/libraries/',
dest: 'dist/js/',
outputfile: 'libraries.min.js'
}
gulp.task('read', (done) => {
fs.readdir(config.src, (err, items) => {
console.log(items);
});
done();
});
//delete the output file(s)
gulp.task('clean', gulp.series('read'), (done) => {
//del is an async function and not a gulp plugin (just standard nodejs)
//It returns a promise, so make sure you return that from this task function
// so gulp knows when the delete is complete
return del([config.dest + config.outputfile]);
});
// Combine and minify all files from the app folder
// This tasks depends on the clean task which means gulp will ensure that the
// Clean task is completed before running the scripts task.
gulp.task('scripts', gulp.series('clean'), (done) => {
//Include all js files but exclude any min.js files
var files = [config.src + '*.js', '!' + config.src + '*.min.js'];
return gulp.src(files)
.pipe(debug())
.pipe(count('## files selected'))
.pipe(uglify())
.pipe(concat(config.outputfile))
.pipe(gulp.dest(config.dest));
});
//Set a default tasks
gulp.task('default', gulp.series('scripts'), (done) => {
});
Which produces the output - including file list for verification there are src files:
[07:46:25] Using gulpfile <path>\gulpfile.js
[07:46:25] Starting 'default'...
[07:46:25] Starting 'scripts'...
[07:46:25] Starting 'clean'...
[07:46:25] Starting 'read'...
[07:46:25] Finished 'read' after 996 μs
[07:46:25] Finished 'clean' after 2.73 ms
[07:46:25] Finished 'scripts' after 4.26 ms
[07:46:25] Finished 'default' after 6.9 ms
[ 'bootstrap-datetimepicker.js',
'bootstrap.min.js',
'chart.min.js',
'cycle.js',
'farbtastic.js',
'jquery-3.2.1.min.js',
'jquery-sortable-min.js',
'moment.min.js',
'ol.min.js',
'pablo.min.js',
'popper.min.js',
'proj4.js',
'promisedIndexDB.js',
'qunit-2.6.1.js',
'toastr.js' ]
If I create an empty file, at dist/js/libraries.min.js it isn't deleted as part of the gulp tasks, however if i move the call to del() outside the gulp tasks it is deleted, so that leads me to assume that its not as simple as a permissions issue, or path issues.
Any idea what I've done wrong?
PS: its on a windows box, running in an admin cmd window.
You were using the wrong signature for the task. The correct one is :
task([taskName], taskFunction)
see task signature
But your tasks look like this:
gulp.task('scripts', gulp.series('clean'), (done) => { // 3 parameters
Merely changing that to:
gulp.task('scripts', gulp.series('clean', (done) => {
...
}));
makes it work - I tested it. So now that task has only two parameters: a task name and a function. Yours had a task name plus two functions.
You would also need to change your default and clean tasks to this proper signature. Also you should call done() at the end of the task as you did with your cb().
Your new code uses task functions, which are better than named tasks for a number of reasons - but now you know what was wrong with your original code. The main body of your scripts task was never being run.
I never worked out what was wrong, but went direct to the doc's and started again (previous version was from a example)..
Works with the below (much simpler) script.
// // include plug-ins
var gulp = require('gulp');
var count = require('gulp-count');
var debug = require('gulp-debug');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var del = require('del');
var config = {
src: 'jspa-scada/dist/libraries/',
dest: 'jspa-scada/dist/js/',
outputfile: 'libraries.min.js'
}
function defaultTask(cb) {
del([config.dest + config.outputfile]);
// Include all js files but exclude any min.js files
var globs = [
config.src + '*.js',
'!' + config.src + '*.min.js'
];
return gulp.src(globs)
.pipe(debug())
.pipe(count('## files selected'))
.pipe(uglify())
.pipe(concat(config.outputfile))
.pipe(gulp.dest(config.dest));
cb();
}
exports.default = defaultTask

How to deploy gulp-ftp, after previos task?

i have a problem with two gulp task in npm.js. First task compile project, next tast deploy it on ftp. If I run them separately - all work, but when i try to use them together, its now work. I think its a stream error. Cuz gulp ftp (second task) finish faster then (first task). Can someone help with this?
First task:
gulp.task('build', ['nib', 'html', 'scripts'], function() {
var removeDist = del.sync('app/dist');
var buildCSS = gulp
.src('app/chache/css/*.css')
.pipe(cssnano())
.pipe(gulp.dest('app/dist/css'));
var buildImg = gulp
.src(['app/html-dev/img/**/*', '!app/html-dev/img/empty.jpg'])
.pipe(imagemin({
interlaced: true,
progressive: true,
svgoPlugins: [{ removeViewBox: false }],
une: [pngquant()]
}))
.pipe(gulp.dest('app/dist/img'));
var buildFonts = gulp
.src(["app/html-dev/fonts/**/*", '!app/html-dev/fonts/empty.woff'])
.pipe(gulp.dest('app/dist/fonts'));
var buildJS = gulp
.src("app/chache/js/**/*")
.pipe(gulp.dest('app/dist/js'));
var buildHhtml = gulp
.src("app/chache/*.html")
.pipe(gulp.dest('app/dist'));
});
Ftp Task:
gulp.task('ftp', ['build'], function () {
return gulp.src('app/dist/**')
.pipe(ftp(ftpinfo))
// you need to have some kind of stream after gulp-ftp to make sure it's flushed
// this can be a gulp plugin, gulp.dest, or any kind of stream
// here we use a passthrough stream
.pipe(gutil.noop());
});
Error:
[13:34:47] Using gulpfile ~\Desktop\test-dist\gulpfile.js
[13:34:47] Starting 'nib'...
[13:34:47] Starting 'html'...
[13:34:47] Starting 'scripts'...
[13:34:47] Finished 'scripts' after 9.31 ms
[13:34:50] Finished 'nib' after 3.35 s
[13:34:50] Finished 'html' after 3.34 s
[13:34:50] Starting 'build'...
[13:34:50] Finished 'build' after 21 ms
[13:34:50] Starting 'ftp'...
[13:34:50] gulp-ftp: No files uploaded
[13:34:50] Finished 'ftp' after 6.5 ms
[13:34:50] gulp-imagemin: Minified 0 images
You need to return the stream from the dependancy task, 'build'. Otherwise the parent task 'ftp' won't wait for 'build'to end.
Since that task has multiple src you need to merge them with merge-stream
var merge = require('merge-stream');
gulp.task('build', ['nib', 'html', 'scripts'], function() {
var removeDist = del.sync('app/dist');
return merge(
gulp
.src('app/chache/css/*.css')
.pipe(cssnano())
.pipe(gulp.dest('app/dist/css')),
gulp
.src(['app/html-dev/img/**/*', '!app/html-dev/img/empty.jpg'])
.pipe(imagemin({
interlaced: true,
progressive: true,
svgoPlugins: [{ removeViewBox: false }],
une: [pngquant()]
}))
.pipe(gulp.dest('app/dist/img')),
gulp
.src(["app/html-dev/fonts/**/*", '!app/html-dev/fonts/empty.woff'])
.pipe(gulp.dest('app/dist/fonts')),
gulp
.src("app/chache/js/**/*")
.pipe(gulp.dest('app/dist/js')),
gulp
.src("app/chache/*.html")
.pipe(gulp.dest('app/dist'))
);
});

Svgmin infinite loop when running inside a task

I'm trying to get svgmin to work in my gulpfile. This is my current config:
var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var sass = require('gulp-sass');
var minify = require('gulp-minify');
var uglify = require('gulp-uglify');
var pump = require('pump');
var concat = require('gulp-concat');
var connect = require('gulp-connect-php');
var svgmin = require('gulp-svgmin');
// Static Server + watching scss/html files
gulp.task('serve', function() {
connect.server({}, function (){
browserSync.init({
proxy: '127.0.0.1:8000'
});
});
gulp.watch("assets/scss/*.scss", ['sass']);
gulp.watch("assets/js/*.js", ['javascripts']);
gulp.watch("assets/img/**/*.svg", ['svg']);
gulp.watch('**/*.php').on('change', function () {
browserSync.reload();
});
});
// Optimize SVG
gulp.task('svg', function() {
return gulp.src('assets/img/**/*.svg')
.pipe(svgmin())
.pipe(gulp.dest('assets/img/'));
browserSync.reload();
});
// Compile sass into CSS & auto-inject into browsers
gulp.task('sass', function() {
return gulp.src([
"node_modules/normalize.css/normalize.css",
'node_modules/animate.css/animate.min.css',
"assets/scss/main.scss"
])
.pipe(sass().on('error', sass.logError))
.pipe(minify())
.pipe(concat('main.css'))
.pipe(gulp.dest("assets/build"))
.pipe(browserSync.stream());
});
// Compile javascripts & refresh browser
gulp.task('javascripts', function (cb) {
pump([
gulp.src([
// Javascript files we need
'assets/js/modernizr.js', // Modernizr
'node_modules/jquery/dist/jquery.min.js', // jQuery
'node_modules/gsap/src/minified/TweenMax.min.js', // GSAP Aninmations
'node_modules/scrollmagic/scrollmagic/uncompressed/ScrollMagic.js', // ScrollMagic Main
'node_modules/scrollmagic/scrollmagic/uncompressed/plugins/animation.gsap.js', // GASP ScrollMagic plugin
'assets/js/main.js' // Main JS file
]),
concat('main.js'),
uglify(),
gulp.dest('assets/build'),
],
cb
);
browserSync.reload();
});
gulp.task('default', ['sass', 'svg', 'javascripts', 'serve']);
When I run gulp svg it runs correctly without any errors. But when I run gulp (and thus the serve task) the svg task ends in a infinite loop. What am I doing wrong here? I want my gulp to minify my SVG files whenever theres a new file or a change, and then update the browser with browerSync.
[15:46:09] Starting 'svg'...
[15:46:10] Finished 'svg' after 823 ms
[15:46:10] Starting 'svg'...
[15:46:11] Finished 'svg' after 609 ms
[15:46:11] Starting 'svg'...
[15:46:11] Finished 'svg' after 618 ms
[15:46:11] Starting 'svg'...
[15:46:12] Finished 'svg' after 630 ms
[15:46:12] Starting 'svg'...
Your problem originates with this watch:
gulp.watch("assets/img/**/*.svg", ['svg']);
This runs the svg task whenever an SVG file is touched. In your svg task you do the following:
return gulp.src('assets/img/**/*.svg')
.pipe(svgmin())
.pipe(gulp.dest('assets/img/'));
This minifies all your SVG files and replaces each file with its minified version. So what happens is:
svg task is run
all SVG files are replaced with their minified version
watch is triggered, because SVG files have been touched
svg task is run
all SVG files are replaced with their minified version
watch is triggered, because SVG files have been touched
etc ...
You need to break that cycle.
One way of doing that is to just place the minified SVG files into the assets/build directory as you do with files in your other tasks:
return gulp.src('assets/img/**/*.svg')
.pipe(svgmin())
.pipe(gulp.dest('assets/build/'));
If you really want to replace the SVG files your can use the gulp-cached plugin. It prevents the SVG files from being overwritten if there are no actual content changes:
var cache = require('gulp-cached');
gulp.task('svg', function() {
return gulp.src('assets/img/**/*.svg')
.pipe(cache('svgmin'))
.pipe(svgmin())
.pipe(gulp.dest('assets/img/'))
.pipe(browserSync.stream());
});
This has the added benefit that your svg task will run faster, since only modified files will need to be processed now.

Why won't browser-sync update my browser?

Awe, why won't browser sync update chrome. =[ I'm using gulp to run browser sync which appears to be hosting correctly. I've set up the server like this in my gulp file:
var gulp = require('gulp');
var browser = require('browser-sync');
var reload = browser.reload;
gulp.task('webserver', function() {
browser({
server:{
baseDir: './'
}
});
});
gulp.task('reload', function(){reload();});
I run the webserver task in webstorm and I get a new chrome tab with a little message saying "Connected to Browser Sync". Awesome. I also get this in the output window.
[18:47:45] Using gulpfile ...\gulpfile.js
[18:47:45] Starting 'webserver'...
[18:47:45] Finished 'webserver' after 27 ms
[BS] Access URLs:
-------------------------------------
Local: http://localhost:3000
External: http://192.168.1.17:3000
-------------------------------------
UI: http://localhost:3001
UI External: http://192.168.1.17:3001
-------------------------------------
[BS] Serving files from: ./
Everything looks great. Then I change some HTML in my index.html and run the reload task. I get this output:
[19:02:55] Using gulpfile ...\gulpfile.js
[19:02:55] Starting 'reload'...
[19:02:55] Finished 'reload' after 121 μs
Process finished with exit code 0
But the browser isn't updates with my latest content. I've tried to boil this down to the most basic code that should work, but I can't get it to update the browser. =[ Am I missing anything that would keep this from working?
TL;DR
I do believe your answer is how you are watching the files, and then calling load. So basically, if you are using sass or less, or typescript, etc. You need to have your browsersync task:
watch for those files first, then execute their task to transpile (compile) to your .css, .js, etc...
Once it detects the changes in the .css, .js, .html files (which will occur after they transpiler tasks converts them to those files), have it reload the browser.
But whether or not you are using those, you still watch all the folders locations and file extensions. This is done by putting all the locations you are watching into an array, and watching the array of files.
NOTE: Browsersync has a separate .watch() from gulp's watch. Using browsersyncs watch function instead of gulp will see new files, where as gulps watch command does not. See example's below.
I apologize for providing such a needlessly verbose response, but I use gulp-cli (gulp 4) w/ multiple task files and external config), and haven't used gulp 3 in a while, so I will try to port it over in a single task to gulp 3.
Some examples
I am providing both versions since gulp 4 may soon be released. And I will just copy and paste mine, and slightly modify it. And that means I will be using the multiple task files version.
So here is an overview of the two versions that I will provide:
The one I use, which is: gulp 4 w/ multiple task files and an external config
The gulpfile
The external task
The external config
I will also include an example sass and typescript config to show globbing with browser-sync's watch task
The gulpfile with the browser-sync task that I will try to port to gulp 3
1. Gulp 4 w/ multiple task files and external config
I will provide some notes in each file as I do in each of my own. And I will provide install instructions if interested, as I do in each of mine as well. This is mostly for copy and paste reasons. And also I will provide the config for sass and typescript, since it is out of scope for the answer, I will not be providing the task files.
And here is a brief overview of the gulp folder structure to help clarify:
| -- Project-Folder/
| | -- gulp/
| | | -- tasks/
| | | ' -- browser-sync.js
| | ' -- config.js
| ' -- gulpfile.js
The gulpfile
gulpfile.js
// =========================================================
// Project: PROJECT-TITLE
//
// NOTES: Using Gulp 4, in order to use, please uninstall gulp 3 globally and locally, and install gulp 4 both globally and locally
// Dependencies: ---
// Global: npm install -g gulpjs/gulp.git#4.0 browser-sync
// Local: npm install --save-dev gulpjs/gulp.git#4.0 browser-sync gulp-load-plugins
// =========================================================
// ------------------------------------------------ Requires
var gulp = require('gulp'),
config = require('./gulp/config'),
plugins = require('gulp-load-plugins')();
// --------------------function to get tasks from gulp/tasks
function getTask(task) {
return require('./gulp/tasks/' + task)(gulp, plugins);
}
// ---------------------------------------------- Gulp Tasks
gulp.task('sass' , getTask( 'sass' ));
gulp.task('ts' , getTask( 'typescript' ));
gulp.task('sync' , getTask( 'browsersync' ));
// --------------------------------------- Default Gulp Task
gulp.task('default', gulp.series(
gulp.parallel('sass', 'ts'), 'sync')
);
The external task file
browser-sync.js
// =========================================================
// Gulp Task: browsersync
// NOTE: Using gulp v4
// Description: Sync sass, typescript, html, and browser
// using an external config, or modify src and config options
// npm install --save-dev browser-sync gulp-typescript gulpjs/gulp.git#4.0
// Options: node-sass gulp-sass || gulp-ruby-sass
// =========================================================
var config = require( '../config.js' );
var browserSync = require( 'browser-sync' ).create();
module.exports = function( gulp, plugins ) {
return function () {
var stream =
// -------------------------------------------- Start Task
browserSync.init( config.browsersync.opts );
browserSync.watch( config.sass.src, gulp.series( 'sass' ) );
browserSync.watch( config.typescript.src, gulp.series( 'ts' ) );
browserSync.watch( config.browsersync.watch ).on( 'change', browserSync.reload );
// ---------------------------------------------- End Task
return stream;
};
};
The external config
NOTE: These configs are easily added into the tasks file if this seems unnecessary. I am only providing so that I can easily copy and paste some tasks from my own project.
// =========================================================
// Project: PROJECT-TITLE
// =========================================================
// ------------------------------------------ Export Configs
module.exports = {
production: false,
// --------------------------------------------- browsersync
browsersync: {
opts: {
server: './src/',
// proxy: 'localhost:3000',
port: 8000
},
watch: [
'./src/assets/styles/css/**/*.css',
'./src/assets/scripts/js/**/*.js',
'./src/**/*.html'
]
},
// ---------------------------------------------------- sass
sass: {
src: [
"./src/assets/styles/sass/**/*.{scss,sass}"
],
opts: { },
outputName: 'main.css',
dest: './src/assets/styles/css/'
},
// ---------------------------------------------- typescript
typescript: {
src: [
'./src/assets/scripts/ts/**/*.ts'
],
dest: './src/assets/scripts/js',
opts: {
noImplicitAny: true,
}
}
}
Gulp 3 version
NOTE: In the config section, I will only be putting the sass and typescript src folders with extensions, and will leave the rest empty as they are not pertinent to this example.
gulpfile.js
// =========================================================
// Project: PROJECT-TITLE
//
// NOTES: Using Gulp 4, in order to use, please uninstall gulp 3 globally and locally, and install gulp 4 both globally and locally
// Dependencies: ---
// Global: npm install -g gulpjs/gulp.git#4.0 browser-sync
// Local: npm install --save-dev gulpjs/gulp.git#4.0 browser-sync gulp-load-plugins
// =========================================================
// ------------------------------------------------ Requires
var gulp = require( 'gulp' ),
sass = require( 'gulp-sass' ),
ts = require( 'gulp-typescript' )
browsersync = require( 'browser-sync' ).create();
// -------------------------------------------------- Config
var config = {
browsersync = {
opts: {
server: './src/',
// proxy: 'localhost:3000',
port: 8000
},
watch: [
'./src/assets/styles/css/**/*.css',
'./src/assets/scripts/js/**/*.js',
'./src/**/*.html'
]
},
sass = { src: './src/assets/styles/sass/**/*.{scss,sass}', ... },
ts = { src: './src/assets/scripts/ts/**/*.ts', ... }
}
// ---------------------------------------------- Gulp Tasks
gulp.task( 'sass', function() {
// task code here
});
gulp.task( 'ts', function() {
// task code here
});
gulp.task('browsersync', [ 'sass', 'ts' ], function() {
browserSync.init( config.browsersync.opts );
// Transpile your preprocessors to their .css, .js, .html versions first
browserSync.watch( config.sass.src, [ 'sass' ] );
browserSync.watch( config.typescript.src, [ 'ts' ] );
// Then under watch, watch all of the locations in an array glob
// such as in the config object at the top of this file.
// Once the preprocessors change to their .css, .js, .html
// counterparts, that will trigger the reload
browserSync.watch( config.browsersync.watch ).on( 'change', browserSync.reload );
});
// --------------------------------------- Default Gulp Task
gulp.task( 'default', [ 'browsersync' ] );
Again, sorry for the very long and detailed response. Just tried for clarity. I hope it helps you and anyone else in the future.

Gulp Livereload in Chrome

The below code seems to work just fine until I go to 1ocalhost:8081...
then I get the message..
<pre>{"tinylr":"Welcome","version":"0.0.5"}</pre>
My directory structure is....
____gulp
| |____build
| | |____images
| | |____index.html
| | |____scripts
| | |____styles
| |____gulpfile.js
| |____node_modules
| |____src
| | |____images
| | |____index.html
| | |____scripts
| | |____styles
Why isn't my html page loading? If I try to browse to
1ocalhost:8081/build/index.html The page wont load and I get the msg
{"error":"not_found","reason":"no such route"}
I've also tried the chrome plugin but I get the below msg when I hit the plugin Could not connect to LiveReload server. Please make sure that LiveReload 2.3 (or later) or another compatible server is running.
I checked the plugin settings from the plugin in Chrome and check the option for file urls
Heres my commented code.....
//sudo npm install gulp -g
// install chrome extension from https://chrome.google.com/webstore/detail/livereload/jnihajbhpnppcggbcgedagnkighmdlei
//Go into the settings from the plugin in Chrome and check the option for file urls: chrome://extensions/
// include gulp
var gulp = require('gulp');
// include plug-ins
var jshint = require('gulp-jshint');
var changed = require('gulp-changed');
var imagemin = require('gulp-imagemin');
var minifyHTML = require('gulp-minify-html');
var concat = require('gulp-concat');
var stripDebug = require('gulp-strip-debug');
var uglify = require('gulp-uglify');
var autoprefix = require('gulp-autoprefixer');
var minifyCSS = require('gulp-minify-css');
var livereload = require('gulp-livereload');
var lr = require('tiny-lr');
var server = lr();
// JS hint task
gulp.task('jshint', function() {
gulp.src('./src/scripts/*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(livereload(server));
});
// minify new images
gulp.task('imagemin', function() {
var imgSrc = './src/images/**/*',
imgDst = './build/images';
gulp.src(imgSrc)
.pipe(changed(imgDst))
.pipe(imagemin())
.pipe(gulp.dest(imgDst))
.pipe(livereload(server));
});
// minify new or changed HTML pages
gulp.task('htmlpage', function() {
var htmlSrc = './src/*.html',
htmlDst = './build';
gulp.src(htmlSrc)
.pipe(changed(htmlDst))
.pipe(minifyHTML())
.pipe(gulp.dest(htmlDst))
.pipe(livereload(server));
});
// JS concat, strip debugging and minify
gulp.task('scripts', function() {
gulp.src(['./src/scripts/lib.js','./src/scripts/*.js'])
.pipe(concat('script.js'))
.pipe(stripDebug())
.pipe(uglify())
.pipe(gulp.dest('./build/scripts/'))
.pipe(livereload(server));
});
// CSS concat, auto-prefix and minify
gulp.task('styles', function() {
gulp.src(['./src/styles/*.css'])
.pipe(concat('styles.css'))
.pipe(autoprefix('last 2 versions'))
.pipe(minifyCSS())
.pipe(gulp.dest('./build/styles/'))
.pipe(livereload(server));
});
// default gulp task
gulp.task('default', ['imagemin', 'htmlpage', 'scripts', 'styles'], function() {
server.listen(8081, function (err) { if (err) return console.log(err);
// watch for HTML changes
gulp.watch('./src/*.html', function() {
gulp.run('htmlpage');
});
// watch for JS changes
gulp.watch('./src/scripts/*.js', function() {
gulp.run('jshint', 'scripts');
});
// watch for IMG changes
gulp.watch('./src/images/*.png', function() {
gulp.run('imagemin');
});
// watch for CSS changes
gulp.watch('./src/styles/*.css', function() {
gulp.run('styles');
});
});
});
</pre>
And the output from gulp looks good...
Bills-MacBook-Pro:gulp Bill$ gulp
[gulp] Using file /Users/Bill/gulp/gulpfile.js
[gulp] Working directory changed to /Users/Bill/gulp
[gulp] Running 'imagemin'...
[gulp] Finished 'imagemin' in 77 ms
[gulp] Running 'htmlpage'...
[gulp] Finished 'htmlpage' in 2.47 ms
[gulp] Running 'scripts'...
[gulp] Finished 'scripts' in 4.05 ms
[gulp] Running 'styles'...
[gulp] Finished 'styles' in 1.09 ms
[gulp] Running 'default'...
[gulp] Finished 'default' in 1.38 ms
gulp.run() has been deprecated. Use task dependencies or gulp.watch task triggering instead.
[gulp] Running 'htmlpage'...
[gulp] Finished 'htmlpage' in 3.5 ms
[gulp] index.html was reloaded.
[gulp] Running 'htmlpage'...
[gulp] Finished 'htmlpage' in 712 μs
[gulp] Running 'htmlpage'...
[gulp] Finished 'htmlpage' in 1.05 ms
[gulp] index.html was reloaded.
That's not how livereload works. It doesn't run a server to load your content — it runs a separate server to notify when content changes.
When you enable livereload*, a small javascript is embedded in your page which listens to the LR server. When you notify the server that a resource was modified, it tells any listeners, which in turn reload the resource from where ever they originally loaded the resource.
If your webapp/site/page is entirely self contained, you can simply open the file:// url to the page you want in your browser, enable livereload, and it should work.
However, if you are dealing with external resources, you should fire up a server of some sort. There's far too many ways for me to select one for you, but you can use connect, express, or some other node library, you could run python -m SimpleHTTPServer in your directory if you have python installed, etc.
If you want to integrate a connect server into your build process, I have a recipe at the bottom of this article.
* You can enable livereload via a browser plugin or using the gulp-embedlr plugin during development, which I prefer since it works across multiple browsers and devices.
1ocalhost:8081 or localhost:8081 ? Perhaps a spelling error on the first letter.

Resources