I have the following folder structure:
theme
assets
build
css
style.css
src
theme
buttons.scss
style.scss
components
hero
hero.html
hero.scss
index.html
Any changes in src theme and any scss file for a component (i.e. hero.scss) should all compile into style.css.
My theme files compile correctly, but my component scss files don't appear in style.css.
Instead, when I run gulp css, a separate css file appears under the build folder, i.e.
build
css
style.css
hero.css
How can I get it to compile everything into style.css?
gulpfile.js
const assetsSRC = 'assets/src/',
assetsDST = 'assets/build/',
components = 'components/';
const gulp = require('gulp'),
sass = require('gulp-sass')(require('sass')),
sourcemaps = require('gulp-sourcemaps'),
fs = require('fs'),
path = require('path'),
merge = require('merge-stream'),
postcss = require('gulp-postcss'),
autoprefixer = require('gulp-autoprefixer'),
plumber = require('gulp-plumber'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
strip = require('gulp-strip-comments');
const componentCSS = components + '**/*.scss',
componentJS = components + '**/*.js',
globalCSS = assetsSRC + 'scss/style.scss';
configCSS = assetsSRC + 'scss/config/**.scss';
themeCSS = assetsSRC + 'scss/theme/**.scss';
globalJS = assetsSRC + 'js/*.js';
libJS = assetsSRC + 'js/lib/*.js';
var sassOptions = {
errLogToConsole: true,
outputStyle: 'compressed'
};
function getFolders(dir) {
return fs.readdirSync(dir).filter(function(file) {
return fs.statSync(path.join(dir, file)).isDirectory();
});
}
function css() {
var folders = getFolders(components);
var tasks = folders.map(function(folder) {
var src = path.join(components, folder);
var dst = path.join(assetsDST + 'css');
return gulp.src(path.join(src, '/**/*.scss'))
.pipe(sourcemaps.init())
.pipe(sass(sassOptions).on('error', sass.logError))
.pipe(autoprefixer('last 2 versions'))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(dst));
});
return merge(tasks);
}
function mainCSS() {
var dst = path.join(assetsDST + 'css/');
return gulp.src(globalCSS, { allowEmpty: true })
.pipe(sourcemaps.init())
.pipe(sass(sassOptions).on('error', sass.logError))
.pipe(autoprefixer('last 2 versions'))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(dst));
}
function libraryJS() {
var dst = path.join(assetsDST + 'JS/lib');
return gulp.src(libJS).pipe(gulp.dest(dst));
}
function watch() {
gulp.watch([globalCSS,configCSS,themeCSS, componentCSS],mainCSS);
}
exports.mainCSS = mainCSS;
exports.mainJS = mainJS;
exports.libraryJS = libraryJS;
exports.css = css;
exports.javascript = javascript;
exports.watch = watch;
const build = gulp.series(watch);
gulp.task('default', build);
Edit
Attempt using gulp-sass-glob:
function css() {
gulp.task('styles', function () {
var src = path(components);
return gulp
.src(src, '/**/*.scss')
.pipe(sassGlob())
.pipe(sourcemaps.init())
.pipe(sass(sassOptions).on('error', sass.logError))
.pipe(autoprefixer('last 2 versions'))
.pipe(sourcemaps.write('.'))
.pipe(sass())
.pipe(gulp.dest(assetsDST + 'css'));
});
}
Re-ran gulp watch (no errors). Made a change and saved hero.scss. Then went into style.css to find css that has been compiled from hero.scss - nothing shows. scss not compiled into style.css
Edit 2
I have the following:
function css() {
var folders = getFolders(components);
var tasks = folders.map(function(folder) {
var src = path.join(components, folder);
var dst = path.join(assetsDST + 'css/');
return gulp.src(path.join(src, '**/*.scss'))
.pipe(sourcemaps.init())
.pipe(sass(sassOptions).on('error', sass.logError))
.pipe(autoprefixer('last 2 versions'))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(dst));
});
return merge(tasks);
}
This is creating individual css files (rather than collating into style.css). I think this one is close, but unsure how to proceed.
Have you tried gulp-sass-glob?
https://www.npmjs.com/package/gulp-sass-glob
Related
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?
I have gulpfile.js from https://github.com/gulpjs/gulp.
I just change folders name for mine.
Task 'gulp' work normally, first 'gulp watch' too. But any another save any less file don't do anything. Just "Finished 'styles' after 1.34 s"
(JS works good)
Any advice?
main.less have less imports with all filles
Folders looks like:
/www
/js
/css
main.less
file.less
file2.less
/lib
file3.less
var gulp = require('gulp');
var less = require('gulp-less');
var babel = require('gulp-babel');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var cleanCSS = require('gulp-clean-css');
var del = require('del');
var paths = {
styles: {
src: 'www/css/main.less',
dest: 'www/css/'
},
scripts: {
src: 'www/js/js/**/*.js',
dest: 'www/js/'
}
};
function clean() {
return del([ 'assets' ]);
}
function styles() {
return gulp.src(paths.styles.src)
.pipe(less())
.pipe(cleanCSS())
// pass in options to the stream
.pipe(rename({
basename: 'main',
suffix: '.min'
}))
.pipe(gulp.dest(paths.styles.dest));
}
function scripts() {
return gulp.src(paths.scripts.src, { sourcemaps: true})
.pipe(babel())
.pipe(uglify())
.pipe(concat('all.min.js'))
.pipe(gulp.dest(paths.scripts.dest));
}
function watch() {
gulp.watch("www/js/js**/*.js", scripts);
gulp.watch("www/css/**/*.less", styles);
}
exports.clean = clean;
exports.styles = styles;
exports.scripts = scripts;
exports.watch = watch;
var build = gulp.series(clean, gulp.parallel(styles, scripts));
gulp.task('build', build);
gulp.task('default', build);
As #Jakub thought, you never actually call your watch task in the code you presented! You probably want something like this:
var build = gulp.series(clean, gulp.parallel(styles, scripts), watch);
I'm working on project that move in new version, when launch sprite became messy and need to be given versioning to check the latest addition only, sprite used now only sprite.png and sprite-2x.png.
But when i generate with gulp css and gulp cssmin(gulp-minify-css), version in sprite imagePath(sprite.png?v4=.1) disappear (in style.css just sprite.png without ?v=4.1).
This is my sprite config too create sprite.png
// Sprites
var gulp = require('gulp'),
config = require('../config').sprite,
spritesmith = require('gulp.spritesmith'),
gulpif = require('gulp-if'),
merge = require('merge-stream');
gulp.task('sprite', function() {
// Normal
var sprite = gulp.src(config.image + '/icons/*.png')
.pipe(spritesmith({
imgName: 'sprite.png',
imgPath: '../img/sprite.png?v=4.1',
cssName: '_helper.spritemap.scss'
}))
.pipe(gulpif('*.png', gulp.dest(config.image),
gulp.dest(config.sass)));
// Retina
var sprite2x = gulp.src(config.image + '/icons-2x/*.png')
.pipe(spritesmith({
imgName: 'sprite-2x.png',
imgPath: '../img/sprite-2x.png?v=4.1',
cssName: '_helper.spritemap-2x.scss',
cssVarMap: function(sprite) {
sprite.name = sprite.name + '-2x';
}
}))
.pipe(gulpif('*.png', gulp.dest(config.image),
gulp.dest(config.sass)));
Result in spritemap scss:
$icon-kustom-white-name: 'icon-kustom-white';
$icon-kustom-white-x: 449px;
$icon-kustom-white-y: 265px;
$icon-kustom-white-offset-x: -449px;
$icon-kustom-white-offset-y: -265px;
$icon-kustom-white-width: 18px;
$icon-kustom-white-height: 21px;
$icon-kustom-white-total-width: 493px;
$icon-kustom-white-total-height: 483px;
$icon-kustom-white-image: '../img/sprite.png?v=4.1';
$icon-kustom-white: (449px, 265px, -449px, -265px, 18px, 21px, 493px,
483px, '../img/sprite.png?v=4.1', 'icon-kustom-white', );
In Style.css
//Style.css
.example {
background-image: url(../img/sprite.png); // Version missing (?v=4.1)
}
This is gulp css config
// CSS task (compile SASS, autoprefixing, and combine media queries)
var gulp = require('gulp'),
config = require('../config').sass,
plumber = require('gulp-plumber'),
changed = require('gulp-changed'),
sass = require('gulp-sass'),
postcss = require('gulp-postcss'),
autoprefixer = require('gulp-autoprefixer'),
mqpacker = require('css-mqpacker'),
browserSync = require('browser-sync'),
minifyCSS = require('gulp-minify-css');
// filever = require('gulp-version-filename');
gulp.task('css', function() {
return gulp.src(config.src)
.pipe(plumber({
errorHandler: function(err) { console.log(err); this.emit('end') }
}))
.pipe(changed(config.dest, { extension: '.css' }))
.pipe(sass({
imagePath: '../img',
sourceComments: true,
outputStyle: 'expanded'
}))
.pipe(postcss([ autoprefixer, mqpacker({sort: true}) ]))
.pipe(gulp.dest(config.dest))
.pipe(browserSync.reload({stream:true}));
});
gulp.task('cssmin', function() {
return gulp.src(config.src)
.pipe(plumber({
errorHandler: function(err) { console.log(err); this.emit('end') }
}))
.pipe(sass({
imagePath: '../img'
}))
.pipe(postcss([ autoprefixer, mqpacker({sort: true}) ]))
.pipe(minifyCSS())
.pipe(gulp.dest(config.dest));
});
Why is it lost?
Is there any other way?
You can easily do it with:
unix-timestamp: https://www.npmjs.com/package/unix-timestamp
gulp-md5: https://www.npmjs.com/package/gulp-md5
I currently have a file structure like this
projects
sites
site-example
css
scss
site-second-example
css
scss
site-third-example
css
scss
***
site-fifty-example
css
scss
I'm trying to write a gulp task that I can run from the projects folder that will look inside the sites folder, and then go through each folder separately, look for any scss files, and then compile them to css.
I tried to follow this recipe but I must be messing it up somehow:
https://github.com/gulpjs/gulp/blob/master/docs/recipes/running-task-steps-per-folder.md
gulpfile.js
var gulp = require('gulp');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var fs = require('fs');
var path = require('path');
var merge = require('merge-stream');
var postcss = require('gulp-postcss');
var autoprefixer = require('autoprefixer');
var output = './**/css';
var sassOptions = {
errLogToConsole: true,
outputStyle: 'expanded'
};
var scriptsPath = './sites';
function getFolders(dir) {
return fs.readdirSync(dir)
.filter(function(file) {
return fs.statSync(path.join(dir, file)).isDirectory();
});
}
gulp.task('sass', function() {
var processors = [
autoprefixer({
browsers: ['last 12 versions']
})
];
var folders = getFolders(scriptsPath);
var tasks = folders.map(function(folder) {
return gulp.src(path.join(scriptsPath, folder, '/**/*.scss'))
.pipe(sourcemaps.init())
.pipe(sass(sassOptions).on('error', sass.logError))
.pipe(postcss(processors))
.pipe(sourcemaps.write('./maps'))
.pipe(gulp.dest(output));
});
return merge(tasks);
});
You can't put a globstar ** in your destination directory like this:
var output = './**/css';
That won't work, because gulp.dest() can't magically guess from context which directory you want your files to end up in.
You have to explicitly construct a destination directory for each folder returned from getFolders(), just as you do for gulp.src():
var tasks = folders.map(function(folder) {
var src = path.join(scriptsPath, folder, 'scss');
var dst = path.join(scriptsPath, folder, 'css');
return gulp.src(path.join(src, '**/*.scss'))
.pipe(sourcemaps.init())
.pipe(sass(sassOptions).on('error', sass.logError))
.pipe(postcss(processors))
.pipe(sourcemaps.write('./maps'))
.pipe(gulp.dest(dst));
});
I'm trying to use gulp-data with gulp-jade in my workflow but I'm getting an error related to the gulp-data plugin.
Here is my gulpfile.js
var gulp = require('gulp'),
plumber = require('gulp-plumber'),
browserSync = require('browser-sync'),
jade = require('gulp-jade'),
data = require('gulp-data'),
path = require('path'),
sass = require('gulp-ruby-sass'),
prefix = require('gulp-autoprefixer'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
process = require('child_process');
gulp.task('default', ['browser-sync', 'watch']);
// Watch task
gulp.task('watch', function() {
gulp.watch('*.jade', ['jade']);
gulp.watch('public/css/**/*.scss', ['sass']);
gulp.watch('public/js/*.js', ['js']);
});
var getJsonData = function(file, cb) {
var jsonPath = './data/' + path.basename(file.path) + '.json';
cb(require(jsonPath))
};
// Jade task
gulp.task('jade', function() {
return gulp.src('*.jade')
.pipe(plumber())
.pipe(data(getJsonData))
.pipe(jade({
pretty: true
}))
.pipe(gulp.dest('Build/'))
.pipe(browserSync.reload({stream:true}));
});
...
// Browser-sync task
gulp.task('browser-sync', ['jade', 'sass', 'js'], function() {
return browserSync.init(null, {
server: {
baseDir: 'Build'
}
});
});
And this is a basic json file, named index.jade.json
{
"title": "This is my website"
}
The error I get is:
Error in plugin 'gulp-data'
[object Object]
You are getting error because in getJsonData you pass required data as first argument to the callback. That is reserved for possible errors.
In your case the callback isn't needed. Looking at gulp-data usage example this should work:
.pipe(data(function(file) {
return require('./data/' + path.basename(file.path) + '.json');
}))
Full example:
var gulp = require('gulp');
var jade = require('gulp-jade');
var data = require('gulp-data');
var path = require('path');
var fs = require('fs');
gulp.task('jade', function() {
return gulp.src('*.jade')
.pipe(data(function(file) {
return require('./data/' + path.basename(file.path) + '.json');
}))
.pipe(jade({ pretty: true }))
.pipe(gulp.dest('build/'));
});
Use this if you're running the task on gulp.watch:
.pipe(data(function(file) {
return JSON.parse(fs.readFileSync('./data/' + path.basename(file.path) + '.json'));
}))