How to gulp and concatenate bower css files - gulp

Using our gulp script, we want to create different compiled & minified css files for vendor (via bower, see screenshot) and custom styles. Our task for the vendor styles does not work as expected, though. We expected it to iterate through the bower_components, grab the css files, concatenate them, minify them and save the generated vendor.min.css to dist/styles. Said vendor.min.css is not generated, however. We tried commenting some of the .pipe() commands in the return statement and suspect that it might have something to do with the concat() function.
Bower components:
Parts of our gulpfile.js including the malfunctioning task:
var gulp = require('gulp'),
sass = require('gulp-sass'),
concat = require('gulp-concat'),
debug = require('gulp-debug'),
bower = require('gulp-main-bower-files'),
uglify = require('gulp-uglify'),
minify = require('gulp-clean-css'),
filter = require('gulp-filter'),
flatten = require('gulp-flatten'),
autoprefix = require('gulp-autoprefixer'),
sourcemaps = require('gulp-sourcemaps'),
rename = require('gulp-rename'),
imagemin = require('gulp-imagemin'),
del = require('del');
/**
* Predefined file-type filters to use with gulp-filter
*/
var filters = {
css: '**/*.css',
js: '**/*.js',
webFonts: ['**/*.otf','**/*.woff*', '**/*.woff2','**/*.ttf','**/*.eot','**/*.svg'],
images: ['**/*.png','**/*.gif','**/*.jpg','**/*.svg'],
movies: []
};
/**
* concatVendorCSS
* Create vendor.min.css from bower main files without bootstrap (as it is included in custom main.css)
* no autoprefixing included: should be done by source package
* scss-Files will be ignored - include them in /assets/styles/main.scss
*/
gulp.task('styles:vendor',['clean:vendor:styles'], function() {
console.log('concatenating vendor css files and moving to dist...');
var filterCSS = filter([filters.css], { restore: true });
return gulp.src('bower.json')
.pipe(bower())
.pipe(filterCSS)
.pipe(sourcemaps.init())
.pipe(flatten())
.pipe(concat('vendor.min.css'))
.pipe(autoprefix(apConfig))
.pipe(minify())
.pipe(sourcemaps.write())
.pipe(gulp.dest('dist/styles/'));
});
bower.json file:
{
"name": "ptype",
"homepage": "-",
"authors": [
"..."
],
"license": "MIT",
"private": true,
"dependencies": {
"css-hamburgers": "^0.5.0",
"bootstrap": "git://github.com/twbs/bootstrap.git#v4.0.0-alpha.6",
"font-awesome": "fontawesome#^4.6.3",
"jquery": "^3.2.1",
"selectize": "^0.12.4",
"swiper": "^4.0.6",
"jquery-focuspoint": "^1.1.3"
},
"overrides": {
"font-awesome": {
"main": [
"./fonts/FontAwesome.otf",
"./fonts/fontawesome-webfont.eot",
"./fonts/fontawesome-webfont.svg",
"./fonts/fontawesome-webfont.ttf",
"./fonts/fontawesome-webfont.woff",
"./fonts/fontawesome-webfont.woff2",
"./scss/font-awesome.scss"
]
}
}
}

You need to change the components that work together. Use 'main-bower-files' instead of 'gulp-main-bower-files' and exchange 'gulp-concat' with 'gulp-group-concat' to combine as shown below.
I left the double filter in order to get a nicer debug output.
var gulp = require('gulp'),
sass = require('gulp-sass'),
groupConcat = require('gulp-group-concat'),
concat = require('gulp-concat'),
debug = require('gulp-debug'),
bowerMain = require('main-bower-files'),
uglify = require('gulp-uglify'),
minify = require('gulp-clean-css'),
filter = require('gulp-filter'),
flatten = require('gulp-flatten'),
autoprefix = require('gulp-autoprefixer'),
sourcemaps = require('gulp-sourcemaps'),
rename = require('gulp-rename'),
imagemin = require('gulp-imagemin'),
gutil = require('gulp-util'),
del = require('del');
/**
* concatVendorCSS
* Create vendor.min.css from bower main files without bootstrap (as it is included in custom main.css)
* no autoprefixing included: should be done by source package
* scss-Files will be ignored - include them in /assets/styles/main.scss
*/
gulp.task('styles:vendor',['clean:vendor:styles'], function(){
console.log('concatenating bower vendor css files into vendor.min.css and moving to ' + sassConfig.outputDirectory + '...');
return gulp.src(bowerMain())
.pipe( filter(filters.css) )
.pipe( debug() )
.pipe( sourcemaps.init() )
.pipe( groupConcat( { 'vendor.min.css': filters.css } ) )
.pipe( autoprefix(apConfig) )
.pipe( minify() )
.pipe( sourcemaps.write('./maps') )
.pipe( gulp.dest('dist/styles/') );
});

Related

Tailwind CSS + Gulp + PurgeCSS Removing Some Classes Used In Code But Compiling Others

I'm currently attempting to use Tailwind CSS with gulp and purgeCSS in a WordPress project.
Everything runs as expected and the CSS files are compiling however certain classes don't make it into the compiled CSS no matter how they're used in the markup.
For example, the background color classes, i.e. "bg-white" are included in various theme files, but whenever the CSS recompiles, that class is purged. It was the same with the "margin-top" classes, but not any of the other margin classes.
Here is my gulp file:
var postcss = require('gulp-postcss');
var cssImport = require('postcss-import');
var gulp = require('gulp');
var cssvars = require('postcss-simple-vars');
var nested = require('postcss-nested');
var autoprefixer = require('autoprefixer');
var cssnano = require('cssnano');
var purgecss = require('gulp-purgecss')
var sass = require('gulp-sass');
var gcmq = require('gulp-group-css-media-queries');
var uglify = require('gulp-uglify-es').default;
var del = require('del');
var concat = require('gulp-concat');
var sourcemaps = require('gulp-sourcemaps');
var gutil = require('gulp-util');
var babel = require('gulp-babel');
// ============================================================================
// Main Tasks
// ============================================================================
// Default task is build
gulp.task('default', ['build']);
// Development task (watch alias)
gulp.task('dev', ['watch']);
// Build task
gulp.task('build', ['clean'], function() {
gulp.start(['styles', 'scripts']);
});
// Styles task
gulp.task('styles', function() {
return gulp.src([
'./assets/sass/*.scss'
])
.pipe(sass().on('error', sass.logError))
// .pipe(sourcemaps.init())
.pipe(postcss([
require('postcss-import'),
require('tailwindcss'),
autoprefixer(),
// cssnano()
], {
syntax: require('postcss-scss')
}))
.pipe(purgecss({
content: ['./*.php', './templates/*.php', './partials/*.php', './components/*.php'],
extractors: [
{
extractor: content => {
return content.match(/[A-Za-z0-9-_:\/]+/g) || []
// return content.match(/[^<>"'`\s]*[^<>"'`\s:]/g) || []
// return content.match(/[^<>"'`\s.()]*[^<>"'`\s.():]/g) || []
//return content.match(/[\w-/:]+(?<!:)/g) || [];
},
extensions: ['css', 'php', 'html']
}
],
safelist: {
standard: [/^[^-]*mt-*/, /^[^-]*bg-opacity-*/, /^[^-]*bg-white/]
}
}))
.pipe(gulp.dest('./assets/css/'))
});
// Scripts task
gulp.task('scripts', function() {
return gulp.src([
'./node_modules/mmenu-light/dist/mmenu-light.js',
'./node_modules/mmenu-light/dist/mmenu-light.polyfills.js',
'./assets/js/util-scripts.js',
'./assets/vendors/micromodal/micromodal.min.js',
'./assets/vendors/waypoints/lib/jquery.waypoints.js',
'./assets/js/core-js.js',
'./assets/js/theme-js.js'
])
// .pipe(sourcemaps.init())
.pipe(babel({
presets: ['#babel/env']
}))
.pipe(concat('theme-js.dist.js'))
.pipe(uglify())
// .pipe(sourcemaps.write())
.pipe(gulp.dest('./assets/dist/js/'))
});
// ============================================================================
// Build Tasks
// ============================================================================
/**
* Clean directories
*
* #since 0.1.0
*/
gulp.task('clean', function() {
del([
'./assets/css/*.css',
'!./assets/css/font-awesome.min.css',
'./assets/js/*.dist.js'
]);
});
// END BUILD
// ============================================================================
// Dev Tasks
// ============================================================================
/**
* Execute tasks when files are change and live reload web page, and servers
*
* #since 0.1.0
*/
gulp.task('watch', function() {
gulp.watch('./assets/sass/**/*.scss', ['styles']);
gulp.watch('./assets/js/*.js', ['scripts']);
// gulp.watch('./assets/images/*', ['images']);
gulp.watch("*.html", ['bs-reload']);
});
I also tried a variety of extractor regex matches, but none of them seem to work.
Oddly enough, when I add this into the theme configuration of my tailwind.config.js file the background class does compile
backgroundColor: {
'white': '#fff'
},
It seems the vast majority of classes are compiling though so unsure if it's my purgeCSS configuration or some other configuration that I'm missing in tailwind?

postcss/precss - convert .scss to .css

I'm usign postcss/precss with gulp to convert my scss markup to valid css. This is my gulpfile.js:
var gulp = require('gulp');
var postcss = require('gulp-postcss');
var precss = require('precss');
var watch = require('gulp-watch');
gulp.task('stream', function () {
var processors = [
precss
];
return watch('src/*.css', { ignoreInitial: false })
.pipe(postcss(processors))
.pipe(gulp.dest('dest'));
});
gulp.task('default', gulp.parallel('stream'));
The problem is that it doesn't change file extensions, so I need to write scss in *.css files, and what I am trying to do is to set it to read scss from *.scss files and output css into *.css files. Can anybody tell me how to achieve that?
Not an expert on this, so I'll just share how we do sass compilation.
We use gulp-concat to concat the files together into one .css file. Your gulp snippet would be as follows:
var gulp = require('gulp');
var postcss = require('gulp-postcss');
var precss = require('precss');
var watch = require('gulp-watch');
var concat = require('gulp-concat');
gulp.task('stream', function () {
var processors = [
precss
];
return watch('src/*.css', { ignoreInitial: false })
.pipe(postcss(processors))
.pipe(concat('FILENAME.css'))
.pipe(gulp.dest('dest'));
});
gulp.task('default', gulp.parallel('stream'));
Don't forget to do npm install --save-dev gulp-concat first!

Compile sass with gulp-sass

I'm trying to compile some .scss with the following Gulp task:
var gulp = require("gulp"),
rimraf = require("rimraf"),
concat = require("gulp-concat"),
cssmin = require("gulp-cssmin"),
uglify = require("gulp-uglify"),
sass = require('gulp-sass');
var paths = {
webroot: "./wwwroot/"
};
paths.sass = paths.webroot + "lib/foundation-apps/scss/**/*.scss";
gulp.task('sass', function () {
gulp.src(paths.sass)
.pipe(sass())
.pipe(gulp.dest(paths.webroot + '/css/'));
});
This is the output of the command:
but the following is the compile result:
Why only the foundation.scss is compiled?
Check the structure of the bower.json file for foundation-apps (in package folder).
If it's the same found on the project github repo, should be something like this:
...
"main": [
"scss/foundation.scss",
"dist/js/foundation-apps.js",
"dist/js/foundation-apps-templates.js"
],
...
which means that only the scss/foundation.scss file will be compiled.
If you want to specify other files, you should create a override on your app bower.json file (on your root path)
Try to append to the end of the file something like this:
...
"overrides": {
"foundation-apps": {
"main": [
"scss/foundation.scss",
... (all the other files you want) ...
"dist/js/foundation-apps.js",
"dist/js/foundation-apps-templates.js"
]
}
}
...
In this way, you can update your versions without override your custom config (for the package folder default bower.json)
hope it helps.

Do not minify already minified files during concatenation and minification

I have a gulp task which minifies CSS files and concatenates them to one file:
gulp.task('minify-css', function() {
'use strict';
var pathsToMinifyAndConcat = [
'css/index.css'
];
var pathsToConcatOnly = [
'lib/css/font-awesome-4.3.0/font-awesome.min.css'
];
var minifyFiles = require('gulp-cssnano');
var concatAllFilesToOneFile = require('gulp-concat');
return gulp.src(
[]
.concat(pathsToMinifyAndConcat)
.concat(pathsToConcatOnly)
)
.pipe(minifyFiles())
.pipe(concatAllFilesToOneFile('application.min.css'))
.pipe(gulp.dest('dist'));
});
But, if some files are already minified (like font-awesome.min.css for example), it should not be minified again - it should be only concatenated, and it should be omitted from the minifying process. Is there a way to do it without hacky solutions (I don't want to use solutions which I can't fully understand - and I'm pretty new to gulp) with preserved files order? I found a plugin to add src files in any point in the pipeline: gulp-add-src, but it seems to be inactive for a while.
There is more than one way of doing what you want. I will give you two examples.
First:
var gulp = require('gulp');
var minify = require('gulp-cssnano');
var concat = require('gulp-concat');
var merge = require('merge-stream');
gulp.task('minify-css', function() {
var pathsToMinify = [
'css/style1.css'
];
var pathsToConcat = [
'css/style2.css'
];
var minStream = gulp.src(pathsToMinify)
.pipe(minify());
var concatStream = gulp.src(pathsToConcat)
return merge(minStream, concatStream)
.pipe(concat('all.css'))
.pipe(gulp.dest('dist'));
});
In this example it is created two different streams. One is minified and the other is not. In the end these two streams are merged, concatenated and then the files are written in the disk.
Second:
var gulp = require('gulp');
var minify = require('gulp-cssnano');
var concat = require('gulp-concat');
var gulpFilter = require('gulp-filter');
gulp.task('minify-css', function() {
var paths = [
'css/style1.css',
'css/style2.css'
];
// Files to minify.
var filter = gulpFilter([
'style1.css'
],
{
restore: true
});
return gulp.src(paths)
.pipe(filter)
.pipe(minify())
.pipe(filter.restore)
.pipe(concat('all.css'))
.pipe(gulp.dest('dist'));
});
In this example, just one stream is created but the vinyl file objects are filtered by gulp-filter and just the filtered ones are minified. Then, all the files originally in the pipeline are restored with filter.restore and concatenated.
There are other possibilities, like creating two different tasks where one just minifies and the other concatenates, but with this approach you would need to write the minified files temporarily in the disk.
Late to the party, as usual, but another option would be to conditionally minify files using gulp-if. Something like this should work:
const gulp = require('gulp'),
gulpif = require('gulp-if'),
concat = require('gulp-concat'),
minifyCss = require('gulp-cssnano');
gulp.task('css', function () {
gulp.src([
'css/index.css',
'lib/css/font-awesome-4.3.0/font-awesome.min.css'
])
.pipe(gulpif(file => !(file.path.includes('.min.css')), minifyCss()))
.pipe(concat('app.min.css'))
.pipe(gulp.dest('dist'));
});
Hope this helps!

Gulp plugin not pulling all files

Trying to use main-bower-files and filters to copy files from bower_components. So far its working except for less. All it is taking is bootstrap.less and not all the .less files.
var gulp = require('gulp'),
gutil = require('gulp-util'),
gulpFilter = require('gulp-filter'),
bowerMain = require('main-bower-files'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
rename = require('gulp-rename');
// Group tasks
gulp.task('default', function() {
gutil.log("Test");
});
// Individual tasks
gulp.task('bower', function() {
var jsFilter = gulpFilter('*.js', {restore: true}),
lessFilter = gulpFilter('*.less');
return gulp.src(bowerMain())
// JS
.pipe(jsFilter)
.pipe(concat('scripts.js'))
.pipe(gulp.dest('./public/js'))
.pipe(uglify())
.pipe(rename({
suffix: '.min'
}))
.pipe(gulp.dest('./public/js'))
.pipe(jsFilter.restore)
// CSS
.pipe(lessFilter)
//.pipe(concat('styles.css'))
.pipe(gulp.dest('./temp'))
});
If I gutil.log bowerMain and its not showing all the less files. What am I doing wrong here?
if you check the main section of bower.json for bootstrap it shows below
"main": [
"less/bootstrap.less",
"dist/js/bootstrap.js"
],
its containing only boostrap.less hence you see only that one less file. Hence nothing wrong with what you are doing...
you can override the main section of boostrap in your bower.json to include other less files if you want, read on how to do it here