Gulp: minify and unminfy tasks - gulp

I am new to gulp so i don't know as much good gulp plugins. I wrote a code for minifying js, css and html using gulp and its plugins which is working fine. But now i am stuck in unminifying code. I don't know which plugins to use which can easily unminify code.
guplfile.js:
var gulp = require('gulp'),
uglify = require('gulp-uglify')
htmlmin = require('gulp-html-minifier')
csso = require('gulp-csso');
gulp.task('min_js', function () {
gulp.src('app/**/*.js')
.pipe(uglify())
.pipe(gulp.dest('min'))
});
gulp.task('min_html', function () {
gulp.src('app/**/*.html')
.pipe(htmlmin({ collapseWhitespace: true }))
.pipe(gulp.dest('min'))
});
gulp.task('min_css', function () {
gulp.src('app/**/*.css')
.pipe(csso())
.pipe(gulp.dest('min'))
});
gulp.task('minify_all', ['min_js', 'min_html', 'min_css']);
//pending
//gulp.task('unminify',[]);

Uglifying/Minifying is attended for production, you should not uglify your code while you are developing (except for testing purpose).
When you start gulp tasks, you have to make sure that you have in one part your "working code", that you will transform into a "destination code".
When you are doing this :
gulp.task('min_js', function () {
gulp.src('app/**/*.js')
.pipe(uglify())
.pipe(gulp.dest('min'))
});
The code on which you are working on is in the app folder, and your transformed code is in the min folder (it's the destination folder).
But, if the min directory is also used in development, just disable the uglify task in development (easier to debug a not-uglifyied file).
There is no need to un-minify your sources, there are still present in app folder.

Related

Confused with combining gulp and webpack with watch

I'm trying to create a gulpfile that allows me to compile scss and js files.
Calling webpack from a gulp task seems to work as expected (simply followed the webpack-stream intro.
However, I'm failing setting up watching for files. It's working as expected for scss files, but not for webpack compilation. It occurs once at launch, block the console, but does not recompile files.
Here is my gulpfile:
'use strict';
var gulp = require('gulp');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var webpackConfig = require('./webpack.config.js');
var webpack = require('webpack-stream');
gulp.task('default', function () {
// place code for your default task here
});
gulp.task('watch', ['sass:watch','webpack:watch']);
gulp.task('sass', function () {
return gulp.src('./Styles/**/*.scss')
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(sourcemaps.write(".",{ ext: '.map' }))
.pipe(gulp.dest('./wwwroot/styles'));
});
gulp.task('sass:watch', function () {
gulp.watch('./Styles/**/*.scss', ['sass']);
});
gulp.task('webpack', function(){
return gulp.src('App/entry.js')
.pipe(webpack( webpackConfig ))
.pipe(gulp.dest('./'));
});
gulp.task('webpack:watch', function(){
var watch = Object.create(webpackConfig);
watch.watch = true;
return gulp.src('App/entry.js')
.pipe(webpack(webpackConfig))
.pipe(gulp.dest('./'));
});
When I run gulp watch, I get this output:
c:\Data\projets\someproject>gulp watch
[13:30:18] Using gulpfile c:\Data\projets\someproject\gulpfile.js
[13:30:18] Starting 'sass:watch'...
[13:30:18] Finished 'sass:watch' after 13 ms
[13:30:18] Starting 'webpack:watch'...
[13:30:22] Version: webpack 1.12.13
Asset Size Chunks Chunk Names
./wwwroot/dist/bundle.js 498 kB 0 [emitted] main
./wwwroot/dist/bundle.js.map 616 kB 0 [emitted] main
[13:30:22] Finished 'webpack:watch' after 3.92 s
[13:30:22] Starting 'watch'...
[13:30:22] Finished 'watch' after 11 µs
However, even if the console does not returns to the prompt, no bundle file is updated, if I update my sources.
I don't believe the issue is in my webpack.config.js file. If I run webpack --watch --color --progress in the prompt, I see the recompilation of bundle whenever a file is modified.
Thanks for clarification, I'm learning javascript ecosystem the hard way :)
In your console output, you should get 'webpack is watching for changes' if you do everything correctly. You have set watch.watch to true, but in the next step you have referenced to the old webpackConfig, for which the watch parameter is not true. You should use:
return gulp.src('App/entry.js')
.pipe(webpack(watch))
.pipe(gulp.dest('./'));
It worked after this change and the gulp watch polls for both the changes. You will also see in your console 'webpack is watching for changes'.
I hope this solves the issue.

How to get gulp-html-minifier's output into gulp-inject-stringified-html?

I'm trying to use these two gulp plugins together:
gulp-html-minifier
gulp-inject-stringified-html
Or put differently, I'm trying to inject the contents of files containing html fragments into my javascript files after they're minified.
When I'm trying to run a straight up gulp build I get this:
Error: ENOENT: no such file or directory, open 'C:\path\to\.temp\template.html'
Here's a repro of my situation. My folder structure:
/src/app.js
/src/template.html
/gulpfile.js
/package.json
My gulpfile.js:
var gulp = require('gulp');
var injectHtml = require('gulp-inject-stringified-html');
var htmlmin = require('gulp-html-minifier');
gulp.task('minify', [], function() {
gulp.src('src/*.html')
.pipe(htmlmin())
.pipe(gulp.dest('.temp'));
});
gulp.task('default', ['minify'], function() {
gulp.src('src/*.js')
.pipe(injectHtml())
.pipe(gulp.dest('.build'));
});
The template.html file:
<div>My Template</div>
The app.js file:
var html = { gulp_inject: "../.temp/template.html" };
Now, if I run minify manually first, things will work as expected. From this I speculate I'm not using Gulp correctly. I reckon I'd need to pipe the result of htmlmin into the injectHtml method. But I fail to see how.
How can I get these two plugins to play together nicely?
You are missing a return in the minify task. It should look like that:
gulp.task('minify', [], function() {
return gulp.src('src/*.html')
.pipe(htmlmin())
.pipe(gulp.dest('.temp'));
});
Without return, the default task doesn't have any way to know that minify finished, so it may start before the minified html file was created.

liveReload html with watch

I've got liveReload working fine with scss and js, but not with html. here are my tasks...
var gulp = require('gulp'),
liveReload = require('gulp-livereload');
gulp.task('watchFiles', function () {
liveReload.listen();
gulp.watch('src/**/*.scss', ['compileSass']);
gulp.watch('src/**/*.html', ['watchHtmlFiles']);
gulp.watch('src/**/*.js', ['bundle-app']);
});
I needed to use run-sequence to assure my templates were built before bundling..and replaceIndex is a simple pipe for index.html over from 'src' to 'dist'
var gulp = require('gulp'),
runSequence = require('run-sequence'),
liveReload = require('gulp-livereload');
gulp.task('watchHtmlFiles', function (callback) {
runSequence('templates', 'bundle-app', 'replaceIndex', callback);
});
I get an error if I include ".pipe(liveReload())" as part of the callback...so I added it to the bundle-app and replaceIndex tasks. But this doesn't work....
this is now working, with no additional changes! The only thing I can attribute this sudden shift is that I was running another angular project with karma running. When that was shut down, live Reload for html files works fine....

How to filter a gulp watch, which watches for CSS changes, in order to let browserSync stream only the actual modified files

I have a gulp watch task:
gulp.watch([
basePath+'/css/**/*.css'
], ['css']);
This task listens to changes of css files and starts the "css" task.
The css task, uses browserSync to stream the changes:
var gulp = require('gulp'),
browserSync = require('browser-sync');
gulp.task('css', function() {
return gulp.src(basePath+'/css/**/*.css', {'read': false})
.pipe(browserSync.stream());
});
The problem is, when I change only 1 css file, browserSync see's all the css files in the folder (due to gulp.src) and, using web-sockets, streams the changes in the browser for all the files.
[BS] 3 files changed (custom.css, custom2.css, main.css)
This happens even if I change only custom2.css
Now, the question:
How to filter the gulp watch, or CSS task, in order to let browserSync stream only the actual modified files? and not all of them...
Any ideas?
You can invoke gulp.watch() with a glob and callback and use the event passed to the callback to know exactly which css file changed.
gulp.watch(basePath+'/css/**/*.css', function(event) {
gulp.src(event.path, {read: false})
.pipe(browserSync.stream());
});
After changing your watch to this, the css task in your example wouldn't be needed.

Gulp Watch and Nodemon conflict

Short of it: started using Gulp recently (convert from Grunt), and am trying to use both Gulp's default watch task (not gulp-watch from npm) for SASS/JS/HTML and gulp-nodemon (from npm) to restart an Express server upon changes. When running just gulp watch, it works fine; and when running gulp server (for nodemon) that works fine. However, using both together (shown below in the configuration of the default task), the watch stuff isn't working. The task is running, and on the CLI gulp shows 'Starting' and 'Finished' for the watch tasks, but the files don't update.
Relevant task configurations:
Concat javascript:
gulp.task('js:app', function(){
return gulp.src([
pathSource('js/application/modules/**/*.js'),
pathSource('js/application/_main.js')
])
.pipe(concat('application.js'))
.pipe(gulp.dest('./build/assets/js')).on('error', utils.log);
});
Nodemon, restart on changes to express app:
gulp.task('express', function(){
return nodemon({script:'server.js', ext:'js', cwd: __dirname + '/express', legacyWatch: true})
.on('restart', function(){
//gulp.run('watch'); // doesn't work :(
});
});
Watch javascript changes, and run js:app for concat'ing.
gulp.task('watch', function(){
gulp.watch(pathSource('js/application/**/*.js'), ['js:app']);
});
Default task, to initialize gulp watch and nodemon simultaneously:
gulp.task('default', ['watch', 'express']);
If anyone has any ideas, thanks in advance!
gulp.run calls have been deprecated, so I'd try a different approach. Since you're already using gulp, may I suggest giving gulp-nodemon a try?
As per gulp-nodemon documentation, you can pass it an array of tasks to execute:
UPDATE: Here's the full gulpfile.js file, together with a working sample on github.
'use strict';
// Main dependencies and plugins
var gulp = require('gulp');
var jshint = require('gulp-jshint');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var nodemon = require('gulp-nodemon');
var assets = 'assets/js/**/*.js';
var publicDir = 'public/javascripts';
// Lint Task
gulp.task('lint', function () {
return gulp.src(assets)
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'));
});
// Concatenate and minify all JS files
gulp.task('scripts', function () {
return gulp.src(assets)
.pipe(concat('global.js'))
.pipe(gulp.dest(publicDir))
.pipe(rename('global.min.js'))
.pipe(uglify())
.pipe(gulp.dest(publicDir));
});
// Watch Files For Changes
gulp.task('watch', function () {
gulp.watch(assets, ['lint', 'scripts']);
});
gulp.task('demon', function () {
nodemon({
script: 'server.js',
ext: 'js',
env: {
'NODE_ENV': 'development'
}
})
.on('start', ['watch'])
.on('change', ['watch'])
.on('restart', function () {
console.log('restarted!');
});
});
// Default Task
gulp.task('default', ['demon']);
This way, you spawn the watch task upon nodemon's start and ensure that the watch task is again triggered whenever nodemon restarts your app.
EDIT: seems you should be calling the on-change event from gulp-nodemon, which will handle compile tasks before the restart event triggers.
EDIT: It seems nodemon's on('change', callback) is removed from their API
FWIW, it seems that using the cwd parameter on gulp-nodemon's configuration actually sets the entire gulp cwd to that directory. This means future tasks will be executed in the wrong directory.
I had this problem when running gulp watch tasks on my frontend server at the same time as nodemon tasks on my backend server (in the same gulpfile), there was a race condition wherein if the nodemon command was executed first, the frontend stuff would actually build into (Home)/backend/frontend instead of (Home)/frontend, and everything would go pearshaped from there.
I found that using watch and script params on gulp-nodemon worked around this (although it still looks like nodemon is watching my entire project for changes rather than the built backend directory).