Source files customization for gulp.js task - gulp

I have a partial of my gulpfile.js as shown below
var paths = {
src: {
css: [
'app/assets/css/bootstrap.min.css',
'app/assets/highlight/styles/monokai_sublime.css'
'app/assets/css/font.css',
'app/assets/css/style.css',
],
js: [
'app/assets/js/jquery.min.js',
'app/assets/js/bootstrap.min.js',
'app/assets/highlight/highlight.pack.js',
'app/assets/js/script.js',
],
},
dest: {
css: 'public/css/',
js: 'public/js/',
}
}
gulp.task('css', function() {
gulp.src(paths.src.css)
// .pipe(autoprefixer())
// .pipe(cssmin())
.pipe(concat('style.css'))
.pipe(gulp.dest(paths.dest.css));
});
gulp.task('js', function() {
gulp.src(paths.src.js)
// .pipe(uglify())
.pipe(concat('script.js'))
.pipe(gulp.dest(paths.dest.js));
});
For the css task I would like to perform autoprefixer() and cssmin() only for some source files then perform concat() for all of them into one single style.css and would like similarity to the js task, that only some source files need to be uglify() then concat() all of them into one single script.js

Related

How to disable gulp encoding images with base64?

So after gulp work, i have encoded images in base64 in css file which size is 2.8mb(((
Here is my gulpfile:
const path = {
stylus: {
src: './src/stylus/**/*.styl',
dest: './build/styles',
},
build: {
dest: 'build/**'
}
}
function stylusTask() {
return src(path.stylus.src)
.pipe(plumber())
.pipe(stylus({
use: nib(),
import: ['nib'],
compress: true
}))
.pipe(dest(path.stylus.dest))
}
You can configure stylus to only encode images smaller than a specified limit. The urls for images which exceed that limit will not be modified.
In this example, only images smaller than 2000 bytes are encoded:
function stylusTask() {
return src(path.stylus.src)
.pipe(plumber())
.pipe(stylus({
use: nib(),
import: ['nib'],
compress: true,
define: {
url: require('stylus').url({
limit:2000
})
}
}))
.pipe(dest(path.stylus.dest))
}
For more information on the url function, see the following documentation:
https://stylus-lang.com/docs/functions.url.html

Browser-sync, scripts and styles reload not working when migrating from gulp 3.x to gulp 4.x

I am trying to upgrade gulp from 3.x to 4.x
When using gulp watch, the styles, scripts and inject function works well.But when I make any file changes the scripts and styles need to be loaded automatically. This is not working.
I have tried adding gulp.series to each function.
function isOnlyChange(event) {
return event.type === 'changed';
}
gulp.watch([
path.join(conf.paths.src, '/app/**/*.css'),
path.join(conf.paths.src, '/app/**/*.scss')
], gulp.series(function (event) {
if (isOnlyChange(event)) {
gulp.series('styles-reload');
} else {
gulp.series('inject-reload');
}
}));
Gulp watch needs to reload styles when I make changes in styles file but this is not performing.
Can someone help me out how to perform in gulp 4.x
You might try something like this:
function myWatch() {
gulp.watch(['./scss/*.scss'], { events: 'change' }, function (cb) {
console.log("here 1");
// gulp.series('styles-reload');
cb();
});
gulp.watch(['./scss/*.scss'], { events: ['add', 'addDir', 'unlink', 'unlinkDir', 'ready', 'error'] }, function (cb) {
console.log("here 2");
// gulp.series('inject-reload');
cb();
});
}
See https://gulpjs.com/docs/en/api/watch#options to see a description of the events you can include in the second gulp.watch.

How make gulp-replace-task replace text in html file?

I have the following text in a index.html file I want to replace with gulp-replace-task:
<img src="assets/images/logo
<img style="width:100px;height:100px;" src="assets/ima
I want to make it such that all instances of "assets" are replaced with "my/stuff".
I tried the following, but it is not working:
gulp.task('default', function() {
gulp.src('./index.html')
.pipe(replace({
patterns: [
{
match: '/assets/g',
replacement: 'my/stuff'
}
]
}))
.pipe(gulp.dest('./'))
Match can be a string but if you want to use regexp remove the quotes ' around the regexp.
gulp.task('default', function() {
gulp.src('./index.html')
.pipe(replace({
patterns: [
{
match: /assets/g,
replacement: 'my/stuff'
}
]
}))
.pipe(gulp.dest('./'))
You may also use module gulp-string-replace which supports manages with regex, string or even functions.
Example:
Regex:
var replace = require('gulp-string-replace');
gulp.task('replace_1', function() {
gulp.src(["./config.js"]) // Every file allown.
.pipe(replace(new RegExp('#env#', 'g'), 'production'))
.pipe(gulp.dest('./build/config.js'))
});
String:
gulp.task('replace_1', function() {
gulp.src(["./config.js"]) // Every file allown.
.pipe(replace('environment', 'production'))
.pipe(gulp.dest('./build/config.js'))
});
Function:
gulp.task('replace_1', function() {
gulp.src(["./config.js"]) // Every file allown.
.pipe(replace('environment', function () {
return 'production';
}))
.pipe(gulp.dest('./build/config.js'))
});

Gulp bundle then minify

I'm creating 3 minified bundles for my application. I have 2 tasks to do this, minify, and bundle. Minify has a dependency on bundle. If I run minify, both tasks run with no errors. The bundles are created, but the minified files are not. If I remove the dependency on bundle, I can then run minify by itself and the minified files are created successfully. This leads me to believe maybe the files are in use when the minify task triggers (because bundle hasn't finished?). How do I cause it to wait until the files are fully ready? Can I pass the stream? Or maybe combine these into a single task? The reason they are not currently a single task is because they output 2 files per bundle (an unminified and a minified bundle).
var outFolder = __dirname + '\\Scripts\\dist';
var appBundles = [
{ scripts: ['Scripts/Common/**/*.js'], output: 'eStore.common.js' },
{ scripts: ['Scripts/Checkout/**/*.js'], output: 'eStore.checkout.js' },
{ scripts: ['Scripts/ProductDetail/**/*.js'], output: 'eStore.product.js' }
];
gulp.task('bundle', bundle);
gulp.task('minify', ['bundle'], minify); // this one doesn't work
gulp.task('minifyOnly', minify); // this one works
function bundle() {
appBundles.forEach(function (appBundle) {
gulp.src(appBundle.scripts)
.pipe(concat(appBundle.output))
.pipe(sourcemaps.init())
.pipe(sourcemaps.write(outFolder + '\\maps'))
.pipe(gulp.dest(outFolder))
.on('error', errorHandler);
});
}
function minify() {
appBundles.forEach(function(appBundle) {
var bundleSrc = outFolder + '\\' + appBundle.output;
gulp.src(bundleSrc)
.pipe(rename({ extname: '.min.js' }))
.pipe(uglify())
.pipe(gulp.dest(outFolder))
.on('error', errorHandler);
});
}
Have the minify task use the same source files that the bundle task uses. 'concat' will be used in both tasks. This way minify doesn't have a dependency on the output from the bundle task.
function minify() {
appBundles.forEach(function (appBundle) {
console.log('Creating minified bundle for: ' + appBundle.output);
gulp.src(appBundle.scripts)
.pipe(concat(appBundle.output))
.pipe(rename({ extname: '.min.js' }))
.pipe(uglify())
.pipe(gulp.dest(outFolder))
.on('error', errorHandler);
});
}
function bundle() {
appBundles.forEach(function (appBundle) {
console.log('Creating bundle and sourcemaps: ' + appBundle.output);
gulp.src(appBundle.scripts)
.pipe(concat(appBundle.output))
.pipe(sourcemaps.init())
.pipe(sourcemaps.write(outFolder + '\\maps'))
.pipe(gulp.dest(outFolder))
.on('error', errorHandler);
});
}

Gulp to combine bower files

I'm aware this has probably been asked before, but I can't seem to be able to ask Google the right questions to find what I need. So I'm possibly thinking about this in the wrong way.
Basically, I need to know if there is a way to use Gulp with Bower so that all css files in subdirectories under bower_components are combined into one styles.css, all js files in subdirectories under bower_components are combined into one scripts.js. Kind of how assetic works in symfony2 to combine assets into single files. Does each 'built' file in each bower_componets subdirectory have to be linked to manually (in the Gulp config file), or is it more common to loop through them programatically?
Thanks
Would something like the below help? It loops through all css files in my 'src' directory and spits out one css file in the 'dist' folder. It does the same for my js files:
// Config
var requireJsRuntimeConfig = vm.runInNewContext(fs.readFileSync('src/app/require.config.js') + '; require;');
requireJsOptimizerConfig = merge(requireJsRuntimeConfig, {
out: 'scripts.js',
baseUrl: './src',
name: 'app/startup',
paths: {
requireLib: 'bower_modules/requirejs/require'
},
include: [
'requireLib',
'components/nav-bar/nav-bar',
'components/home-page/home',
'text!components/about-page/about.html'
],
insertRequire: ['app/startup'],
bundles: {
// If you want parts of the site to load on demand, remove them from the 'include' list
// above, and group them into bundles here.
// 'bundle-name': [ 'some/module', 'another/module' ],
// 'another-bundle-name': [ 'yet-another-module' ]
}
});
// Discovers all AMD dependencies, concatenates together all required .js files, minifies them
gulp.task('js', function () {
return rjs(requireJsOptimizerConfig)
.pipe(uglify({ preserveComments: 'some' }))
.pipe(gulp.dest('./dist/'));
});
// Concatenates CSS files, rewrites relative paths to Bootstrap fonts, copies Bootstrap fonts
gulp.task('css', function () {
var bowerCss = gulp.src('src/bower_modules/components-bootstrap/css/bootstrap.min.css')
.pipe(replace(/url\((')?\.\.\/fonts\//g, 'url($1fonts/')),
appCss = gulp.src('src/css/*.css'),
combinedCss = es.concat(bowerCss, appCss).pipe(concat('css.css')),
fontFiles = gulp.src('./src/bower_modules/components-bootstrap/fonts/*', { base: './src/bower_modules/components-bootstrap/' });
return es.concat(combinedCss, fontFiles)
.pipe(gulp.dest('./dist/'));
});
there is a way and its honestly really simple. you can install "gulp-run" to your npm devDependencies and then use the run to execute bower install.
var gulp = require('gulp'),
del = require('del'),
run = require('gulp-run'),
sass = require('gulp-sass'),
cssmin = require('gulp-minify-css'),
browserify = require('browserify'),
uglify = require('gulp-uglify'),
concat = require('gulp-concat'),
jshint = require('gulp-jshint'),
browserSync = require('browser-sync'),
source = require('vinyl-source-stream'),
buffer = require('vinyl-buffer'),
reactify = require('reactify'),
package = require('./package.json'),
reload = browserSync.reload;
/**
* Running Bower
*/
gulp.task('bower', function() {
run('bower install').exec();
})
/**
* Cleaning lib/ folder
*/
.task('clean', function(cb) {
del(['lib/**'], cb);
})
/**
* Running livereload server
*/
.task('server', function() {
browserSync({
server: {
baseDir: './'
}
});
})
/**
* sass compilation
*/
.task('sass', function() {
return gulp.src(package.paths.sass)
.pipe(sass())
.pipe(concat(package.dest.style))
.pipe(gulp.dest(package.dest.lib));
})
.task('sass:min', function() {
return gulp.src(package.paths.sass)
.pipe(sass())
.pipe(concat(package.dest.style))
.pipe(cssmin())
.pipe(gulp.dest(package.dest.lib));
})
/**
* JSLint/JSHint validation
*/
.task('lint', function() {
return gulp.src(package.paths.js)
.pipe(jshint())
.pipe(jshint.reporter('default'));
})
/** JavaScript compilation */
.task('js', function() {
return browserify(package.paths.app)
.transform(reactify)
.bundle()
.pipe(source(package.dest.app))
.pipe(gulp.dest(package.dest.lib));
})
.task('js:min', function() {
return browserify(package.paths.app)
.transform(reactify)
.bundle()
.pipe(source(package.dest.app))
.pipe(buffer())
.pipe(uglify())
.pipe(gulp.dest(package.dest.lib));
})
/**
* Compiling resources and serving application
*/
.task('serve', ['bower', 'clean', 'lint', 'sass', 'js', 'server'], function() {
return gulp.watch([
package.paths.js, package.paths.jsx, package.paths.html, package.paths.sass
], [
'lint', 'sass', 'js', browserSync.reload
]);
})
.task('serve:minified', ['bower', 'clean', 'lint', 'sass:min', 'js:min', 'server'], function() {
return gulp.watch([
package.paths.js, package.paths.jsx, package.paths.html, package.paths.sass
], [
'lint', 'sass:min', 'js:min', browserSync.reload
]);
});
what is really beautiful with this setup I just posted is this is making a custom gulp run called "serve" that will run your setup with a development server (with live reload and much better error intelligence) all you have to do is go to your directory and type "gulp serve" and it'll run bower install and build everything for you. obviously the folder structure is different so you will need to make some modifications, but hopefully this shows how you can run bower with gulp :)
Something like the below was what I was looking for, except I don't like having to add the paths manually. This is why I prefer something like CommonJS for Javascript. I definitely remember seeing a way in which CSS files were picked up automatically from the bower_components folder, I believe it was in the Wordpress Roots project (based on the settings/overrides in bower.json).
gulp.task('css', function () {
var files = [
'./public/bower_components/angular-loading-bar/build/loading-bar.css',
'./public/bower_components/fontawesome/css/font-awesome.css'
];
return gulp.src(files, { 'base': 'public/bower_components' })
.pipe(concat('lib.css'))
.pipe(minifyCss())
.pipe(gulp.dest('./public/build/css/')
);
});
gulp.task('js-lib', function () {
var files = [
'public/bower_components/jquery/dist/jquery.js',
'public/bower_components/bootstrap-sass/assets/javascripts/bootstrap.js'
];
return gulp.src(files, { 'base': 'public/bower_components/' })
.pipe(sourcemaps.init())
.pipe(uglify({ mangle: false }))
.pipe(concat('lib.js'))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest('./public/build/js/')
);
});
You can use gulp-main-bower-files library to add the main files of packages in .bower.json instead to declare them manually