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

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?

Related

gulp-file-include and BrowserSync Doesn't Reflect the Changes to Browser

I am trying to use gulp-file-include for include some common sections like header or footer from /src/includes folder into any .html pages in a project tree along with BrowserSync to refresh changes.
When I use gulp command from command line it's compiling all files into /dist folder without problems (I hope). But after, if I change anything from /src/index.html it doesn't reflect changes to browser or write changes into /dist/index.html.
I can't figure out exactly where the problem is. You can see the project from this Git repo and here is my gulpfile.js content:
var gulp = require('gulp');
var autoprefixer = require('gulp-autoprefixer');
var plumber = require('gulp-plumber');
var gutil = require('gulp-util');
var concat = require('gulp-concat');
var cleanCSS = require('gulp-clean-css');
var rename = require("gulp-rename");
var sass = require('gulp-sass');
var uglify = require('gulp-uglify');
var browserSync = require('browser-sync').create();
var sourcemaps = require("gulp-sourcemaps");
var fileinclude = require("gulp-file-include");
// File Paths
var CSS_PATH = { src: "./src/sass/*.scss", dist: "./dist/css/"};
var JS_PATH = { src: "./src/js/*.js", dist: "./dist/js/"};
var HTML_PATH = { src: "./src/*.html", dist: "./dist/html/*.html"};
var INCLUDES_PATH = "./src/includes/**/*.html";
var JQUERY_PATH = "node_modules/jquery/dist/jquery.min.js";
// Error Handling
var gulp_src = gulp.src;
gulp.src = function() {
return gulp_src.apply(gulp, arguments)
.pipe(plumber(function(error) {
// Output an error message
gutil.log(gutil.colors.red('Error (' + error.plugin + '): ' + error.message));
// emit the end event, to properly end the task
this.emit('end');
})
);
};
// Styles
gulp.task('styles', function() {
return gulp.src(CSS_PATH["src"])
.pipe(sass())
.pipe(autoprefixer('last 2 versions'))
.pipe(sourcemaps.init())
.pipe(gulp.dest(CSS_PATH["dist"]))
.pipe(cleanCSS())
.pipe(sourcemaps.write())
.pipe(concat("main.css", {newLine: ""}))
.pipe(gulp.dest(CSS_PATH["dist"]))
.pipe(browserSync.reload({ stream: true }))
});
// Scripts
gulp.task('scripts', function() {
return gulp.src([JS_PATH["src"], JQUERY_PATH])
.pipe(uglify())
.pipe(concat('main.min.js'))
.pipe(gulp.dest(JS_PATH["dist"]));
});
// File Include
gulp.task('fileinclude', function() {
return gulp.src(HTML_PATH["src"])
.pipe(fileinclude({
prefix: '##',
basepath: 'src/includes'
}))
.pipe(gulp.dest('dist'));
});
// BrowserSync
gulp.task('browserSync', function() {
browserSync.init({
server: {
baseDir: 'dist/'
},
open: false,
browser: "Google Chrome",
notify: true,
notify: {
styles: {
top: 'auto',
bottom: '0',
borderRadius: '4px 0 0 0',
opacity: .9
}
},
snippetOptions: {
rule: {
match: /<\/body>/i,
fn: function (snippet, match) {
return snippet + match;
}
}
}
})
})
// Watch task
gulp.task('watch', ['fileinclude', 'browserSync'], function() {
gulp.watch(CSS_PATH["src"], ['styles']);
gulp.watch(JS_PATH["src"], ['scripts']);
gulp.watch(INCLUDES_PATH, ['fileinclude']);
gulp.watch([HTML_PATH["src"], HTML_PATH["src"]], browserSync.reload);
});
gulp.task('default', ['fileinclude', 'styles', 'scripts', 'browserSync', 'watch' ]);
I seem to have it working. I added the following to the end of the 'scripts' and 'fileinclude' tasks:
.pipe(browserSync.reload({ stream: true }))
// File Include
gulp.task('fileinclude', function() {
return gulp.src(HTML_PATH.src)
.pipe(fileinclude({
prefix: '##',
basepath: 'src/includes'
}))
.pipe(gulp.dest('dist'))
.pipe(browserSync.reload({ stream: true }))
});
// Scripts
gulp.task('scripts', function() {
// return gulp.src([JS_PATH["src"], JQUERY_PATH])
return gulp.src(JS_PATH.src)
.pipe(uglify())
.pipe(concat('main.min.js'))
.pipe(gulp.dest(JS_PATH.dist))
.pipe(browserSync.reload({ stream: true }))
});
so that the browser is reloaded after any changes to those two groups. I changed the 'watch' task to:
// Watch task
// gulp.task('watch', ['fileinclude', 'browserSync'], function() {
// 'browserSync' is already running from 'default' task so remove it from above
// 'fileinclude' is called below only where it is needed, not for changes to js/scss files
gulp.task('watch', function() {
gulp.watch(CSS_PATH.src, ['styles']);
gulp.watch(JS_PATH.src, ['scripts']);
gulp.watch(INCLUDES_PATH, ['fileinclude']);
// gulp.watch([HTML_PATH["src"], HTML_PATH["src"]], browserSync.reload);
// the above looks for changes to the source and immediately reloads,
// before any changes are made to the dist/html
// Watch for changes in the html src and run 'fileinclude'
// browserSync reload moved to end of 'fileinclude'
gulp.watch([HTML_PATH.src], ['fileinclude']);
});
Edit: to handle the subsequent question about gulp failing to watch new files, I have made some changes to my original answer. But you should really be using gulp4.0 now IMO. Gulp3.9.x relied on a library that was problematic in watching for new, deleted or renamed files.
You will need two more plugins:
var watch = require("gulp-watch");
var runSequence = require("run-sequence");
The gulp-watch plugin is better at watching for new, etc. files, but doesn't take 'tasks' as arguments but instead it takes functions as arguments so that is why I used run-sequence. [You could rewrite your tasks as regular functions - but then you might as well shift to gulp4.0].
Then use this 'watch' task:
gulp.task('watch', function () {
watch(CSS_PATH.src, function () {
runSequence('styles');
});
watch(JS_PATH.src, function () {
runSequence('scripts');
});
watch(INCLUDES_PATH, function () {
runSequence('fileinclude');
});
watch([HTML_PATH.src], function () {
runSequence('fileinclude');
});
});

gulp-sass with browsersync inject not working

// variable
// -----------------------------------------------------------------------------
var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();
// task
// -----------------------------------------------------------------------------
gulp.task('styles', function() {
return gulp.src([
'./src/assets/styles/*.scss'
], {
base: './src/assets/styles/'
})
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./dist/assets/styles/'))
.pipe(browserSync.stream());
});
gulp.task('browserSync', function() {
browserSync.init({
server: {
baseDir: './dist/'
}
});
gulp.watch('./dist/*.html').on('change', browserSync.reload);
gulp.watch('./src/assets/styles/**/*.scss', ['styles']);
gulp.watch('./dist/assets/scripts/*.js').on('change', browserSync.reload);
});
How can make above code working? The scripts and html part working, but scss part not, when scss file change, styles task has start and finish with no error, the html file has body tag, but the browser do not inject the new css file.
Check this example, it may help you with a few tweaks in paths:
/**
* This example:
* Uses the built-in BrowserSync server for HTML files
* Watches & compiles SASS files
* Watches & injects CSS files
*/
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var gulp = require('gulp');
var sass = require('gulp-sass');
var filter = require('gulp-filter');
// Browser-sync task, only cares about compiled CSS
gulp.task('browser-sync', function() {
browserSync({
server: {
baseDir: "./"
}
});
});
// Sass task, will run when any SCSS files change.
gulp.task('sass', function () {
return gulp.src('scss/styles.scss')
.pipe(sass({includePaths: ['scss']})) // compile sass
.pipe(gulp.dest('css')) // write to css dir
.pipe(filter('**/*.css')) // filter the stream to ensure only CSS files passed.
.pipe(reload({stream:true})); // inject into browsers
});
// Default task to be run with `gulp`
gulp.task('default', ['sass', 'browser-sync'], function () {
gulp.watch("scss/*.scss", ['sass']);
});

How to append the main.css file through Roots's Sage gulpfile?

I'm very new to gulp and seeing as how complex the Roots's Sage gulpfile is, I'm so lost as to which block of code I should put in my code in.
The usage examples for both packages is as follows:
CSS Shrink
var gulp = require('gulp');
var cssshrink = require('gulp-cssshrink');
gulp.task('default', function() {
gulp.src('css/**/*.css')
.pipe(cssshrink())
.pipe(gulp.dest('dist/css/'));
});
Combine Media Queries
var cmq = require('gulp-combine-media-queries');
gulp.task('cmq', function () {
gulp.src('src/**/*.css')
.pipe(cmq({
log: true
}))
.pipe(gulp.dest('dist'));
});
Manifest.json file:
{
"dependencies": {
"main.js": {
"files": [
"scripts/main.js"
],
"main": true
},
"main.css": {
"files": [
"styles/main.scss"
],
"main": true
},
"customizer.js": {
"files": [
"scripts/customizer.js"
]
},
"jquery.js": {
"bower": [
"jquery"
]
}
},
"config": {
"devUrl": "http://yaharga/"
}
}
I tried to put it in the Styles task at the gulpfile.js, but nothing happened:
// ## Globals
var argv = require('minimist')(process.argv.slice(2));
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync').create();
var changed = require('gulp-changed');
var concat = require('gulp-concat');
var flatten = require('gulp-flatten');
var gulp = require('gulp');
var gulpif = require('gulp-if');
var imagemin = require('gulp-imagemin');
var jshint = require('gulp-jshint');
var lazypipe = require('lazypipe');
var less = require('gulp-less');
var merge = require('merge-stream');
var cssNano = require('gulp-cssnano');
var plumber = require('gulp-plumber');
var rev = require('gulp-rev');
var runSequence = require('run-sequence');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var cmq = require('gulp-combine-media-queries');
var cssshrink = require('gulp-cssshrink');
// See https://github.com/austinpray/asset-builder
var manifest = require('asset-builder')('./assets/manifest.json');
// `path` - Paths to base asset directories. With trailing slashes.
// - `path.source` - Path to the source files. Default: `assets/`
// - `path.dist` - Path to the build directory. Default: `dist/`
var path = manifest.paths;
// `config` - Store arbitrary configuration values here.
var config = manifest.config || {};
// `globs` - These ultimately end up in their respective `gulp.src`.
// - `globs.js` - Array of asset-builder JS dependency objects. Example:
// ```
// {type: 'js', name: 'main.js', globs: []}
// ```
// - `globs.css` - Array of asset-builder CSS dependency objects. Example:
// ```
// {type: 'css', name: 'main.css', globs: []}
// ```
// - `globs.fonts` - Array of font path globs.
// - `globs.images` - Array of image path globs.
// - `globs.bower` - Array of all the main Bower files.
var globs = manifest.globs;
// `project` - paths to first-party assets.
// - `project.js` - Array of first-party JS assets.
// - `project.css` - Array of first-party CSS assets.
var project = manifest.getProjectGlobs();
// CLI options
var enabled = {
// Enable static asset revisioning when `--production`
rev: argv.production,
// Disable source maps when `--production`
maps: !argv.production,
// Fail styles task on error when `--production`
failStyleTask: argv.production,
// Fail due to JSHint warnings only when `--production`
failJSHint: argv.production,
// Strip debug statments from javascript when `--production`
stripJSDebug: argv.production
};
// Path to the compiled assets manifest in the dist directory
var revManifest = path.dist + 'assets.json';
// ## Reusable Pipelines
// See https://github.com/OverZealous/lazypipe
// ### CSS processing pipeline
// Example
// ```
// gulp.src(cssFiles)
// .pipe(cssTasks('main.css')
// .pipe(gulp.dest(path.dist + 'styles'))
// ```
var cssTasks = function(filename) {
return lazypipe()
.pipe(function() {
return gulpif(!enabled.failStyleTask, plumber());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.init());
})
.pipe(function() {
return gulpif('*.less', less());
})
.pipe(function() {
return gulpif('*.scss', sass({
outputStyle: 'nested', // libsass doesn't support expanded yet
precision: 10,
includePaths: ['.'],
errLogToConsole: !enabled.failStyleTask
}));
})
.pipe(concat, filename)
.pipe(autoprefixer, {
browsers: [
'last 2 versions',
'android 4',
'opera 12'
]
})
.pipe(cssNano, {
safe: true
})
.pipe(function() {
return gulpif(enabled.rev, rev());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.write('.', {
sourceRoot: 'assets/styles/'
}));
})();
};
// ### JS processing pipeline
// Example
// ```
// gulp.src(jsFiles)
// .pipe(jsTasks('main.js')
// .pipe(gulp.dest(path.dist + 'scripts'))
// ```
var jsTasks = function(filename) {
return lazypipe()
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.init());
})
.pipe(concat, filename)
.pipe(uglify, {
compress: {
'drop_debugger': enabled.stripJSDebug
}
})
.pipe(function() {
return gulpif(enabled.rev, rev());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.write('.', {
sourceRoot: 'assets/scripts/'
}));
})();
};
// ### Write to rev manifest
// If there are any revved files then write them to the rev manifest.
// See https://github.com/sindresorhus/gulp-rev
var writeToManifest = function(directory) {
return lazypipe()
.pipe(gulp.dest, path.dist + directory)
.pipe(browserSync.stream, {match: '**/*.{js,css}'})
.pipe(rev.manifest, revManifest, {
base: path.dist,
merge: true
})
.pipe(gulp.dest, path.dist)();
};
// ## Gulp tasks
// Run `gulp -T` for a task summary
// ### Styles
// `gulp styles` - Compiles, combines, and optimizes Bower CSS and project CSS.
// By default this task will only log a warning if a precompiler error is
// raised. If the `--production` flag is set: this task will fail outright.
gulp.task('styles', ['wiredep'], function() {
var merged = merge();
manifest.forEachDependency('css', function(dep) {
var cssTasksInstance = cssTasks(dep.name);
if (!enabled.failStyleTask) {
cssTasksInstance.on('error', function(err) {
console.error(err.message);
this.emit('end');
});
}
merged.add(gulp.src(dep.globs, {base: 'styles'})
.pipe(cssTasksInstance));
});
/************************* This is where I added it! *************************/
gulp.src(path.dist + 'styles/main.css')
.pipe(cssshrink())
.pipe(cmq())
.pipe(gulp.dest(path.dist + 'styles/main.css'));
return merged
.pipe(writeToManifest('styles'));
});
// ### Scripts
// `gulp scripts` - Runs JSHint then compiles, combines, and optimizes Bower JS
// and project JS.
gulp.task('scripts', ['jshint'], function() {
var merged = merge();
manifest.forEachDependency('js', function(dep) {
merged.add(
gulp.src(dep.globs, {base: 'scripts'})
.pipe(jsTasks(dep.name))
);
});
return merged
.pipe(writeToManifest('scripts'));
});
// ### Fonts
// `gulp fonts` - Grabs all the fonts and outputs them in a flattened directory
// structure. See: https://github.com/armed/gulp-flatten
gulp.task('fonts', function() {
return gulp.src(globs.fonts)
.pipe(flatten())
.pipe(gulp.dest(path.dist + 'fonts'))
.pipe(browserSync.stream());
});
// ### Images
// `gulp images` - Run lossless compression on all the images.
gulp.task('images', function() {
return gulp.src(globs.images)
.pipe(imagemin({
progressive: true,
interlaced: true,
svgoPlugins: [{removeUnknownsAndDefaults: false}, {cleanupIDs: false}]
}))
.pipe(gulp.dest(path.dist + 'images'))
.pipe(browserSync.stream());
});
// ### JSHint
// `gulp jshint` - Lints configuration JSON and project JS.
gulp.task('jshint', function() {
return gulp.src([
'bower.json', 'gulpfile.js'
].concat(project.js))
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'))
.pipe(gulpif(enabled.failJSHint, jshint.reporter('fail')));
});
// ### Clean
// `gulp clean` - Deletes the build folder entirely.
gulp.task('clean', require('del').bind(null, [path.dist]));
// ### Watch
// `gulp watch` - Use BrowserSync to proxy your dev server and synchronize code
// changes across devices. Specify the hostname of your dev server at
// `manifest.config.devUrl`. When a modification is made to an asset, run the
// build step for that asset and inject the changes into the page.
// See: http://www.browsersync.io
gulp.task('watch', function() {
browserSync.init({
files: ['{lib,templates}/**/*.php', '*.php'],
proxy: config.devUrl,
snippetOptions: {
whitelist: ['/wp-admin/admin-ajax.php'],
blacklist: ['/wp-admin/**']
}
});
gulp.watch([path.source + 'styles/**/*'], ['styles']);
gulp.watch([path.source + 'scripts/**/*'], ['jshint', 'scripts']);
gulp.watch([path.source + 'fonts/**/*'], ['fonts']);
gulp.watch([path.source + 'images/**/*'], ['images']);
gulp.watch(['bower.json', 'assets/manifest.json'], ['build']);
});
// ### Build
// `gulp build` - Run all the build tasks but don't clean up beforehand.
// Generally you should be running `gulp` instead of `gulp build`.
gulp.task('build', function(callback) {
runSequence('styles',
'scripts',
['fonts', 'images'],
callback);
});
// ### Wiredep
// `gulp wiredep` - Automatically inject Less and Sass Bower dependencies. See
// https://github.com/taptapship/wiredep
gulp.task('wiredep', function() {
var wiredep = require('wiredep').stream;
return gulp.src(project.css)
.pipe(wiredep())
.pipe(changed(path.source + 'styles', {
hasChanged: changed.compareSha1Digest
}))
.pipe(gulp.dest(path.source + 'styles'));
});
// ### Gulp
// `gulp` - Run a complete build. To compile for production run `gulp --production`.
gulp.task('default', ['clean'], function() {
gulp.start('build');
});
Ideally, I would need to capture the main.css code and implement the cmq and cssshrink to it just before it is finally exported into the distribution folder.
I followed the post on Roots Discourse to help me do it; will update with full answer once done.

gulp browsersync sass partials

I have the following problem and don't know whats going wrong with my gulpfile. Everything is working fine and my sass files are being compiled and the browser refreshed when changing something.
But if I add a new partial file and import it into my _base.scss, browsersync is only recognizing the change in that partial and is not compiling the whole sass file & reloading the browser. Does anyone know how to solve this problem? I could not figure out a good solution.
Thanks!
Here's my gulpfile.js
/*=============================================>>>>>
= gulpfile - all the gulptasks are here =
===============================================>>>>>*/
/*----------- variables -----------*/
// gulp
var gulp = require('gulp');
// css stuff
var postcss = require('gulp-postcss');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var sourcemaps = require('gulp-sourcemaps');
var cssnext = require('postcss-cssnext');
var lost = require('lost');
var csswring = require('csswring');
// javascript
var babel = require('gulp-babel');
// jade
var jade = require('gulp-jade-php');
// browser sync
var browserSync = require('browser-sync').create();
var reload = browserSync.reload;
/*----------- tasks -----------*/
// style task
gulp.task('styles', function(){
var processors = [
autoprefixer,
cssnext,
lost,
csswring
];
return gulp.src('./scss/**/*.scss')
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(postcss(processors))
.pipe(sourcemaps.write())
.pipe(gulp.dest('./css/'))
.pipe(reload({stream: true}));
;
});
// javascript task
gulp.task('javascript', function(){
return gulp.src('./js/*.js')
.pipe(babel())
.pipe(gulp.dest('./js/dist/'))
.pipe(reload({stream: true}));
});
// jade task
gulp.task('jade', function(){
return gulp.src('./jade/*.jade')
.pipe(jade())
.pipe(gulp.dest('./templates/'))
.pipe(reload({stream: true}));
});
// browser sync
gulp.task('browserSync', function(){
var files = [
'./scss/**/*.scss',
'./css/style.css',
'./*.php',
'./templates/**/*.php',
'./js/*js',
'./jade/*jade'
];
browserSync.init(
files, {
proxy : 'localhost:8888/jobs/heisaplan/',
});
});
// watching the files for changes
gulp.task('watch', function(){
gulp.watch('./scss/**/*.scss', ['styles']).on('change', browserSync.reload);
gulp.watch('./js/*.js', ['javascript']).on('change', browserSync.reload);
gulp.watch('./jade/**/*.jade', ['jade']).on('change', browserSync.reload);
gulp.watch('./templates/**/*.php').on('change', browserSync.reload);
gulp.watch('./*.php').on('change', browserSync.reload);
});
// default gulp task
gulp.task('default', ['watch', 'browserSync', 'styles', 'javascript', 'jade']);

gulp sass watch task #import issue

I wanted to try gulp with sass and run into problems.
I have following sass directory:
main.scss //all custom styling
mixins.scss //custom mixins
variables.scss //custom variables
style.scss //file that imports all the above with bootstrap and fontawesome
When i run gulp, everything compiles and there are no errors, i get the correct sytle.min.css with all the styling included.
But then i change one of the watched files (main.scss || mixins.scss || variables.scss) I get one of the following errors: "undefined variable", "no mixin named ..." accordingly.
Also if I change and save main.scss i get no errors but none of the custom scss files get included into css, only bootstrap with fontawesome get compiled.
What is wrong with my setup?
gulpfile.js
var gulp = require('gulp'),
sass = require('gulp-sass'),
notify = require("gulp-notify"),
concat = require('gulp-concat'),
minifycss = require('gulp-minify-css'),
uglify = require('gulp-uglify'),
rename = require('gulp-rename')
bower = require('gulp-bower')
merge = require('merge-stream')
watch = require('gulp-watch');
var config = {
destPath: './dist',
sassPath: './src/sass',
jsPath: './src/js',
bowerDir: './src/components'
}
gulp.task('bower', function() {
return bower()
.pipe(gulp.dest(config.bowerDir));
});
gulp.task('icons', function() {
var fontawesome = gulp.src(config.bowerDir + '/font-awesome/fonts/**.*')
.pipe(gulp.dest('./src/fonts'));
var bootstrap = gulp.src(config.bowerDir + '/bootstrap-sass/assets/fonts/bootstrap/**.*')
.pipe(gulp.dest('./src/fonts/bootstrap'));
return merge(fontawesome, bootstrap);
});
gulp.task('sass', function() {
console.log(config.sassPath);
var stream = gulp.src([config.sassPath + '/style.scss'])
.pipe(sass().on('error', sass.logError))
// .pipe(concat('style.css'))
.pipe(minifycss())
.pipe(rename('style.min.css'))
.pipe(gulp.dest(config.destPath));
return stream;
});
gulp.task('js', function() {
var stream = gulp.src([config.bowerDir + '/jquery/dist/jquery.js', config.bowerDir + '/bootstrap-sass/assets/javascripts/bootstrap.js', config.jsPath + '/*.js'])
.pipe(concat('script.js'))
.pipe(uglify())
.pipe(rename('script.min.js'))
.pipe(gulp.dest(config.destPath));
return stream;
});
gulp.task('watch', function(){
watch([config.sassPath + '/*.scss'], function(event, cb) {
gulp.start('sass');
});
watch([config.jsPath + '/*.js'], function(event, cb) {
gulp.start('js');
});
});
gulp.task('default', ['bower', 'icons', 'js','sass', 'watch']);
style.scss
#import "./variables.scss";
#import "./mixins.scss";
#import "../components/bootstrap-sass/assets/stylesheets/bootstrap.scss";
#import "../components/font-awesome/scss/font-awesome.scss";
#import "./main.scss";
Ok, so I fixed it by adding timeout to my watch task before calling sass task:
watch([config.sassPath + '/*.scss'], function(event, cb) {
setTimeout(function(){
gulp.start('sass');
}, 1000);
});
It's either the IDE (sublime 2) on save delay or server ping problem.