I have a gulp file that I just wrote and I'm new at this. It's working but I have more tasks than I think I need.
Can anyone help me string the javascript tasks together as one task?
I need four separate js files all uglified when I'm done.
relevant code snippet from gulpfile.js:
var gulp = require('gulp')
uglify = require('gulp-uglify'),
rename = require('gulp-rename'),
concat = require('gulp-concat'),
notify = require('gulp-notify'),
cache = require('gulp-cache'),
del = require('del');
gulp.task('clean', function(cb) {
del(['css/*', 'js/min/*'], cb)
});
gulp.task('featuretest', function() {
return gulp.src('js/feature-test.js')
.pipe(rename({suffix: '.min'}))
.pipe(uglify())
.pipe(gulp.dest('js/min'))
});
// This file: '/js/excanvas.min.js' is only loaded via lte IE8 conditional statement
gulp.task('excanvas', function() {
return gulp.src('js/polyfills/excanvas.js')
.pipe(rename({suffix: '.min'}))
.pipe(uglify())
.pipe(gulp.dest('js/min'))
});
// This file: '/js/charts.min.js' is only used on very few pages
gulp.task('charts', function() {
return gulp.src(['js/highcharts-4.0.1.js', 'js/usfa-theme.js'])
.pipe(concat('charts.js'))
.pipe(rename({suffix: '.min'}))
.pipe(uglify())
.pipe(gulp.dest('js/min'))
});
// This file: '/js/main.min.js' is a concat of 'libs/jquery', a few polyfills (except excanvas.js and the highcharts)
gulp.task('scripts', function() {
return gulp.src(['js/libs/*.js', 'js/plugins/*.js', 'js/polyfills/*.js', '!js/excanvas.js', '!js/highcharts-4.0.1.js', 'js/custom.js'])
.pipe(concat('main.js'))
.pipe(rename({suffix: '.min'}))
.pipe(uglify())
.pipe(gulp.dest('js/min'))
.pipe(notify({ message: 'Scripts task complete' }));
});
gulp.task('watch', function() {
// Watch .js files
gulp.watch('js/**/*.js', ['featuretest', 'excanvas', 'charts', 'scripts']);
});
gulp.task('default', ['clean'], function() {
gulp.start('featuretest', 'excanvas', 'charts', 'scripts');
});
What I was trying to do:
var gulp = require('gulp')
uglify = require('gulp-uglify'),
rename = require('gulp-rename'),
concat = require('gulp-concat'),
notify = require('gulp-notify'),
cache = require('gulp-cache'),
del = require('del');
gulp.task('clean', function(cb) {
del(['css/*', 'js/min/*'], cb)
});
gulp.task('scripts', function() {
// This file: '/js/feature-test.js' is loaded in the doc <head>
return gulp.src('js/feature-test.js')
.pipe(rename({suffix: '.min'}))
.pipe(uglify())
.pipe(gulp.dest('js/min'))
// This file: '/js/excanvas.min.js' is only loaded via lte IE8 conditional statement at the end of the doc
return gulp.src('js/polyfills/excanvas.js')
.pipe(rename({suffix: '.min'}))
.pipe(uglify())
.pipe(gulp.dest('js/min'))
// This file: '/js/charts.min.js' is only used on very few pages and is loaded only when needed at the end of the doc
return gulp.src(['js/highcharts-4.0.1.js', 'js/usfa-theme.js'])
.pipe(concat('charts.js'))
.pipe(rename({suffix: '.min'}))
.pipe(uglify())
.pipe(gulp.dest('js/min'))
// This file: '/js/main.min.js' is a concat of 'libs/jquery', a few polyfills (except excanvas.js and the high charts), it is loaded at the end of every doc
return gulp.src(['js/libs/*.js', 'js/plugins/*.js', 'js/polyfills/*.js', '!js/excanvas.js', '!js/highcharts-4.0.1.js', 'js/custom.js'])
.pipe(concat('main.js'))
.pipe(rename({suffix: '.min'}))
.pipe(uglify())
.pipe(gulp.dest('js/min'))
.pipe(notify({ message: 'Scripts task complete' }));
});
gulp.task('watch', function() {
// Watch .js files
gulp.watch('js/**/*.js', ['scripts']);
});
gulp.task('default', ['clean'], function() {
gulp.start('scripts');
});
If you're asking the question how do I combine separate operations into a single task, you can combine streams with gulp-util.
var gulp = require('gulp')
uglify = require('gulp-uglify'),
util = require('gulp-util');
gulp.task('scripts', function() {
var featureTest = gulp.src('js/feature-test.js')...
var excanvas = gulp.src('js/polyfills/excanvas.js')...
var charts = gulp.src(['js/highcharts-4.0.1.js', 'js/usfa-theme.js'])...
var scripts = gulp.src(['js/libs/*.js', 'js/plugins/*.js', 'js/polyfills/*.js', '!js/excanvas.js', '!js/highcharts-4.0.1.js', 'js/custom.js'])...
// combine streams
return util.combine(featureTest, excanvas, charts, scripts);
});
This will give you a single task, but it's not any faster. If you're not forcing things to be sequential, gulp will be as fast as it's gonna be.
Related
I have successfully got all my scss including bootstraps to combine into one minified file using gulp. Now I am trying to do the same with my js and bootstraps. The problem is that uglify keeps throwing errors at me like Unexpected token: name ($) etc. And won't minify / compile bootstrap js because of this. Now I'm starting to believe I am going the wrong way about this.
This is my file structure:
app/js(my.js files in here)/vendor/bootstrap/js/src/(boostrap js files here)
As you can see, what I have done is just copy the bootstrap js files into my files in the hope that they would be minified / compiled along with mine. But with the scss I imported the files like you usually do. So am I doing this the wrong way?
here's my gulp.js code
var gulp = require('gulp');
var sass = require('gulp-sass');
var cleanCss = require('gulp-clean-css');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var gulpSequence = require('gulp-sequence');
var autoPrefixer = require('gulp-autoprefixer');
var concat = require('gulp-concat');
var jshint = require('gulp-jshint');
var csslint = require('gulp-csslint');
var htmlReporter = require('gulp-csslint-report');
var plumber = require('gulp-plumber');
var sourcemaps = require('gulp-sourcemaps');
//plumber error
var onError = function (err) {
console.log(err);
};
//create sourcemaps, convert scss to css, lint check, minify and prefix
gulp.task('css', function(){
return gulp.src('app/scss/**/*.scss')
.pipe(plumber({
errorHandler: onError
}))
.pipe(sourcemaps.init())
.pipe(sass())
.pipe(csslint())
.pipe(htmlReporter())
.pipe(cleanCss())
.pipe(rename({
suffix: '.min'
}))
.pipe(autoPrefixer({
browsers: ['last 3 versions'],
cascade: false
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('dist/css'))
});
//create sourcemaps, lint check, compile into one file, minify
gulp.task('js', function() {
return gulp.src('app/js/**/*.js')
.pipe(plumber({
errorHandler: onError
}))
.pipe(sourcemaps.init())
.pipe(jshint())
.pipe(jshint.reporter('gulp-jshint-html-reporter', {
filename: __dirname + '/jshint-output.html',
createMissingFolders : false
}))
.pipe(concat('all.js'))
.pipe(uglify())
.pipe(rename({
suffix: '.min'
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('dist/js'))
});
//copy php files to app
gulp.task('phpCopy', function(){
return gulp.src('app/*.php')
.pipe(plumber({
errorHandler: onError
}))
.pipe(gulp.dest('dist'));
});
//functions to run on file save
gulp.task('watch', function(){
gulp.watch('app/scss/**/*.scss', ['css']);
gulp.watch('app/*.php', ['phpCopy']);
gulp.watch('app/js/**/*.js', ['js']);
});
gulp.task('default', ['css', 'js', 'phpCopy']);
To any body struggling with this here is what I did to fix this problem.
//create sourcemaps, lint check, compile into one file, minify
gulp.task('js', function() {
return gulp.src([
'node_modules/jquery/dist/jquery.js',
'node_modules/bootstrap/dist/js/bootstrap.js',
'app/js/**/*.js'
])
.pipe(plumber({
errorHandler: onError
}))
.pipe(sourcemaps.init())
.pipe(jshint())
.pipe(jshint.reporter('gulp-jshint-html-reporter', {
filename: __dirname + '/jshint-output.html',
createMissingFolders : false
}))
.pipe(concat('all.js'))
.pipe(uglify())
.pipe(rename({
suffix: '.min'
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('dist/js'))
});
I had to point to the bootstrap file inside node_modules instead of copying them into my files. Here's a tutorial that helped me http://george.webb.uno/posts/gulp-and-npm-for-front-end-web-development
And if you copy this code be aware that sourcemaps isn't working properly yet. I will continue to work on this.
So I have the following basic project structure that I use throughout all my projects:
Where the src folder looks like this:
I use Pug(Jade), sass compiling and useref js compilation.
This is my Jade views structure:
And this is my Jade index file:
This is my Jade scripts file, that is included in the index:
This is my pre-build index file, which is constructed by the index.pug:
And this is the build version of the index file:
My Gulpfile looks like this:
var gulp = require('gulp'),
sass = require('gulp-sass'),
plumber = require('gulp-plumber'),
changed = require('gulp-changed'),
gutil = require('gulp-util'),
pug = require('gulp-pug'),
concat = require('gulp-concat'),
browserSync = require('browser-sync').create(),
useref = require('gulp-useref'),
uglify = require('gulp-uglify'),
gulpIf = require('gulp-if'),
cssnano = require('gulp-cssnano'),
imagemin = require('gulp-imagemin'),
cache = require('gulp-cache'),
del = require('del'),
cssAdjustUrlPath = require('gulp-css-adjust-url-path'),
runSequence = require('run-sequence');
function handleError(err) {
gutil.beep();
console.log(err.toString());
this.emit('end');
}
gulp.task('sass', function () {
return gulp.src('src/scss/**/*.scss')
.pipe(plumber({
errorHandler: handleError
}))
.pipe(sass()) // Using gulp-sass
.pipe(gulp.dest('src/css'))
.pipe(browserSync.reload({
stream: true
}));
});
gulp.task('sass-dist', function () {
return gulp.src('src/scss/**/*.scss')
.pipe(cssAdjustUrlPath(/(url\(['"]?)[/]?(assets)/g))
.pipe(sass()) // Using gulp-sass
.pipe(gulp.dest('dist/css'))
});
gulp.task('views', function buildHTML() {
return gulp.src('src/views/*.pug')
.pipe(changed('src', {
extension: '.html'
}))
.pipe(pug({
pretty: true
}))
.pipe(gulp.dest('src/'))
});
gulp.task('views-dist', function buildHTML() {
return gulp.src('src/views/*.pug')
.pipe(changed('src', {
extension: '.html'
}))
.pipe(pug({
pretty: true
}))
.pipe(gulp.dest('dist/'))
});
gulp.task('watch', ['browserSync', 'views', 'sass'], function () {
gulp.watch('src/scss/**/*.scss', ['sass']);
gulp.watch('src/views/**/*.pug', ['views']);
// Reloads the browser whenever HTML or JS files change
gulp.watch('src/js/**/*.js', browserSync.reload);
gulp.watch('src/*.html', browserSync.reload);
});
gulp.task('browserSync', function () {
browserSync.init({
server: {
baseDir: 'src'
},
port: 3000
});
});
gulp.task('useref', function () {
return gulp.src('src/*.html')
.pipe(useref())
.pipe(gulpIf('*.js', uglify()))
// Minifies only if it's a CSS file
.pipe(gulpIf('*.css', cssnano()))
.pipe(gulp.dest('dist'));
});
gulp.task('useref-dist', function () {
return gulp.src('src/**/*.html')
.pipe(useref())
.pipe(gulpIf('*.js', uglify()))
// Minifies only if it's a CSS file
.pipe(gulpIf('*.css', cssnano()))
.pipe(gulp.dest('dist'));
});
gulp.task('images', function () {
return gulp.src('src/images/**/*.+(png|jpg|jpeg|gif|svg)')
// Caching images that ran through imagemin
.pipe(cache(imagemin({
interlaced: true
})))
.pipe(gulp.dest('src/images/'));
});
gulp.task('images-dist', function () {
return gulp.src('src/images/**/*.+(png|jpg|jpeg|gif|svg)')
// Caching images that ran through imagemin
.pipe(cache(imagemin({
interlaced: true
})))
.pipe(gulp.dest('dist/images/'));
});
gulp.task('fonts', function () {
return gulp.src('src/fonts/**/*')
.pipe(gulp.dest('dist/fonts'));
});
gulp.task('clean:dist', function () {
return del.sync('dist');
});
gulp.task('build', function (callback) {
runSequence('clean:dist', ['sass-dist', 'useref-dist', 'images-dist', 'fonts', 'views-dist'],
callback
);
});
gulp.task('default', function (callback) {
runSequence(['views', 'sass', 'browserSync', 'watch'],
callback
);
});
When I run the build task gulp build, all is well, except the relative/absolute paths inside the outputted CSS files, and the JS that runs the final product, whereas fonts/backgrounds/icons and JS functionality is not translated into the final build.
What is wrong with my Gulp file, and how can I fix it?
I have been struggling for a while now and it is fairly frustrating to be honest.
The problem:
I created a gulpfile for my static website, and all i want to do is use browserSync, to compile sass into css and to minify the script and css files. Everything works fine, excluding one thing:
When I run "gulp" everything loads, besides de css file, which is located in "CSS/". Apparently the server thinks that the css file is ("CSS/style.css/") a folder actually.
Screenshot with the console error:
image
the css file is located in "css/style.css"
"use strict";
let paths = {
script: "js/*.js",
minifiedScript: 'script.min.js',
cssPath: "css/*.css",
productionFolder: "production",
sassPath: "scss/*.scss",
htmlFiles: "*.html"
};
const gulp = require('gulp');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
const sourcemaps = require('gulp-sourcemaps');
const del = require('del');
const browserSync = require('browser-sync').create();
const cssMin = require('gulp-css');
const sass = require('gulp-sass');
const inject = require('gulp-inject');
const rename = require("gulp-rename");
gulp.task('browserSync', function() {
browserSync.init({
server: {
baseDir: "./"
}
});
});
gulp.task('sass', function () {
return gulp.src(paths.sassPath)
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./css'))
.pipe(browserSync.stream());
});
gulp.task('index', function () {
var target = gulp.src('index.html');
// It's not necessary to read the files (will speed up things), we're only after their paths:
var sources = gulp.src([paths.script,paths.cssPath], {read: false});
return target.pipe(inject(sources))
.pipe(gulp.dest(''));
});
gulp.task('cssMinify', function(){
return gulp.src(paths.cssPath)
.pipe(cssMin())
.pipe(gulp.dest(paths.productionFolder + "/minified css"))
.pipe(browserSync.stream());
});
gulp.task('clean', function() {
// You can use multiple globbing patterns as you would with `gulp.src`
return del(['build']);
});
gulp.task('scripts', ['clean'], function() {
// Minify and copy the JS file
return gulp.src(paths.script)
.pipe(sourcemaps.init())
.pipe(uglify())
.pipe(concat(paths.minifiedScript))
.pipe(sourcemaps.write())
.pipe(gulp.dest(paths.productionFolder + "/minified JS"));
});
gulp.task('jsMinify:watch', function() { gulp.watch(paths.script, ['scripts']) });
gulp.task('sass:watch', function() { gulp.watch(paths.sassPath, ['sass']) });
gulp.task('cssMinify:watch', function() { gulp.watch(paths.cssPath, ['cssMinify']) });
gulp.task('html:watch', function() { gulp.watch(paths.htmlFiles).on('change', browserSync.reload) });
gulp.task('default', ['sass', 'index', 'cssMinify', 'clean', 'html:watch', 'jsMinify:watch', 'sass:watch', 'cssMinify:watch','browserSync', 'scripts']); // DEVELOPMENT
Hi im trying to get a gulp watch on the go in my gulp.js file. It needs to run my sass and minify it and set to destination folder on watch. Can anybody help please?
var gulp = require('gulp');
var sass = require('gulp-sass');
var minifyCss = require('gulp-minify-css');
var uglify = require('gulp-uglify');
var watch = require('gulp-watch');
var htmlmin = require('gulp-html-minifier');
gulp.task('sass', function(){
return gulp.src('scss/styles.scss')
.pipe(sass()) // Converts Sass to CSS with gulp-sass
.pipe(minifyCss())
.pipe(gulp.dest('dest'))
});
gulp.task('minify-css', function() {
return gulp.src('dest/*.css')
.pipe(minifyCss())
.pipe(gulp.dest('dest'));
});
gulp.task('compress', function() {
return gulp.src('lib/*.js')
.pipe(uglify())
.pipe(gulp.dest('dist'));
});
gulp.task('minify-html', function() {
gulp.src('*.html')
.pipe(htmlmin({collapseWhitespace: true}))
.pipe(gulp.dest(''))
});
// Watch Files For Changes
gulp.task('watch', function(){
gulp.watch('scss/*.scss', ['sass']);
// Other watchers
})
// Run all Refinedby Tasks
gulp.task('all', ['sass']);
You need to load the watcher when you call your "all task command".
gulp.task('all', ['sass'], function() {
gulp.watch('scss/*.scss', ['sass']);
});
or
gulp.task('all', ['sass'], function() {
gulp.start('watch');
});
or if you do not want to change your code just add
// Run all Refinedby Tasks
gulp.task('all', ['sass', 'watch']);
I am using a gulp.js file to convert my less code to css and then update the website automatically on save using BrowserSync however, when I save the file no changes have been made. the code for my gulp.js file is below:
var gulp = require('gulp'),
less = require('gulp-less'),
uglifycss = require("gulp-uglifycss"),
path = require('path'),
watch = require('gulp-watch'),
autoprefixer = require('gulp-autoprefixer'),
browserSync = require('browser-sync'),
uglify = require('gulp-uglify'),
sourcemaps = require('gulp-sourcemaps'),
jshint = require('gulp-jshint'),
imageResize = require('gulp-image-resize'),
rename = require("gulp-rename"),
changed = require("gulp-changed"),
plumber = require("gulp-plumber"),
cmq = require('gulp-combine-media-queries');
var run = require('gulp-run');
//gulp.src(['js/**/*.js', '!js/**/*.min.js'])
gulp.task('default', function () {
var devProxy = "mywebsite.dev.chand.co";
// }
browserSync({
proxy: devProxy,
files: "library/css/*.css"
});
//gulp.watch('./library/less/**/*.less', ['compile-css']);
gulp.watch('./library/less/**/*.less', ['compile-css']);
gulp.watch(['./library/js/*.js', '!./library/js/main-built.js'], ['javascript']);
});
gulp.task('javascript', function() {
gulp.src(['./library/js/*.js','./library/js/components/*.js', '!./library/js/main-built.js', '!./library/js/cf7.js']) // ignore vendor stuff
.pipe(plumber())
.pipe(jshint())
.pipe(jshint.reporter('default'));
// gulp.src(['./library/js/**/*.js', '!./library/js/require.js'])
//.pipe(uglify())
// .pipe(gulp.dest('library/dist/js'));
run('r.js -o build.js').exec();
});
gulp.task('compile-css', function () {
gulp.src('./library/less/main.less')
.pipe(plumber())
.pipe(sourcemaps.init())
.pipe(less())
.pipe(autoprefixer())
//.pipe(uglifycss())
.pipe(sourcemaps.write('./maps'))
.pipe(gulp.dest('./library/css/'));
gulp.src('./library/less/admin.less')
.pipe(plumber())
.pipe(sourcemaps.init())
.pipe(less())
.pipe(autoprefixer())
//.pipe(uglifycss())
.pipe(sourcemaps.write('./maps'))
.pipe(gulp.dest('./library/css/'));
gulp.src('./library/less/editor-style.less')
.pipe(plumber())
.pipe(sourcemaps.init())
.pipe(less())
.pipe(autoprefixer())
//.pipe(uglifycss())
.pipe(sourcemaps.write('./maps'))
.pipe(gulp.dest('./library/css/'));
gulp.src('./library/less/style-bootstrap.less')
.pipe(plumber())
//.pipe(sourcemaps.init())
.pipe(less())
.pipe(autoprefixer())
//.pipe(uglifycss())
.pipe(gulp.dest('./library/css/'));
return;
});
gulp.task('dist-css', function () {
gulp.src('./library/less/main.less')
.pipe(less())
.pipe(autoprefixer())
.pipe(cmq({
log: true
}))
.pipe(uglifycss())
.pipe(gulp.dest('./library/css/'));
gulp.src('./library/less/admin.less')
//.pipe(sourcemaps.init())
.pipe(less())
.pipe(autoprefixer())
.pipe(uglifycss())
//.pipe(sourcemaps.write('./maps'))
.pipe(gulp.dest('./library/css/'));
gulp.src('./library/less/editor-style.less')
//.pipe(sourcemaps.init())
.pipe(less())
.pipe(autoprefixer())
.pipe(uglifycss())
//.pipe(sourcemaps.write('./maps'))
.pipe(gulp.dest('./library/css/'));
});
gulp.task('resize-images', function () {
// this doesn't happen automatically, because it's a bit intensive, it should be done when we need.
var originalName;
gulp.src("images/src/**/*.{jpg,png}")
.pipe(changed("images/dist"))
// This isn't ideal, but it'll work fine
// Make sure that you go BIGGEST FIRST because of piping
// Need to change renaming to the wordpress convention
// need to specify heights?
// need to do lossless optimisation
// remember to set new name as well as new size for each resize.
.pipe(imageResize({
imageMagick : true,
width : 200
}))
.pipe(rename(function (path) {
originalName = path.basename;
path.basename = originalName + "-200";
}))
.pipe(gulp.dest("images/dist"))
.pipe(imageResize({
imageMagick : true,
width : 100
}))
.pipe(rename(function (path) {
path.basename = originalName + "-100";
}))
.pipe(gulp.dest("images/dist"));
});
It looks like you are having a caching problem I read more about this for css + browsersync.
this post might help you.
This could be your solution then.
move your watch to a seperate task
gulp.task('watch', ['browser-sync'], function(){
gulp.watch('./library/less/**/*.less', ['compile-css']);
gulp.watch('./library/css/**/*.css').on('change', browserSync.reload);
});
and let it depend on browser-sync
gulp.task('browser-sync', function() {
var devProxy = "mywebsite.dev.chand.co";
browserSync({
proxy: devProxy,
files: "library/css/*.css"
});
});
And then change default to
gulp.task('default', 'watch');
read more about reloading + browserSync here
It's also worth trying to delete your compressed CSS and JavaScript files manually.
rm -f web/css/compressed/style.css for example
...and then trying a gulp build again.