Getting proper sourcemaps (gulp sass + cleanCss + prefixer + uncss) - sass

What is best way to chain gulp for compiling sass into clean css (prefixed, un-CSSed and minified).
Following example creates sourcemaps, but they are pointing to wrong line numbers in source files when viewed in browser inspector.
var plugins = require('gulp-load-plugins')(),
bourbon = require('node-bourbon').includePaths,
neat = require('node-neat').includePaths;
gulp.task('default', function () {
return gulp.src('src/scss/**/*.scss')
.pipe(plugins.sourcemaps.init())
.pipe(plugins.sass({includePaths: bourbon, includePaths: neat}))
.on('error',plugins.util.log.bind(plugins.util, 'Sass Error'))
.pipe(plugins.concat('styles.css'))
.pipe(plugins.uncss({html: ['dist/**/*.html']}))
.pipe(plugins.autoprefixer())
.pipe(plugins.cleanCss())
.pipe(plugins.sourcemaps.write('.'))
.pipe(gulp.dest('dist/css/'));
});
In an attempt to fix this problem I tried to output sourcemaps before autoprefixer and cleanCss but it results in an error related to "Neat" and "Burbon" paths: Error: Broken #import declaration of "../neat" Broken #import declaration of "../colors" Broken #import declaration of "../variables" Broken #import declaration of "../grid" Broken #import declaration of "../tables"

i work with this task, using CSSO instead of your cleanCSS but use whatever you want, the tricky part is the sourcemaps, sometimes mess up the paths.
Declare a source path
Init SourceMaps
Compile SCSS into CSS
Add the right prefix support
Paste SourceMaps in the CSS file generated pointing to the SCSS files
Compress the CSS file ( this probably remove the sourcemaps unless you told package to save comments )
Declare a dest path
Gulpfile: SASS Task
const gulp = require('gulp'),
autoprefixer = require('gulp-autoprefixer'),
csso = require('gulp-csso'),
sass = require('gulp-sass'),
sourcemaps = require('gulp-sourcemaps');
gulp.task('sass', ['sass'], () => {
return gulp
.src('src/scss/**/*.scss')
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(autoprefixer({ browser: ['last 2 version', '> 5%'] }))
.pipe(sourcemaps.write())
.pipe(csso())
.pipe(gulp.dest('dist/css'));
});

Related

Gulpfile.js - how to get .min.css, .css, and .css.map files on gulp.watch?

Ok, I've done lots of research on this, but on a drupal site, I have a zurb foundation theme and am super happy with it. The only problem I'm having is when I customize the scss components. I'm using gulp to compile it and it is recreating the css file fine. However, I would like to get it to ALSO give me the min.css file and the css.map file, but I can't seem to figure it out. I've tried many different iterations on the gulpfile.js but here is my latest.
It only produces the css file.
var sassFiles = './themes/zurb_foundation/scss/**/*.scss',
cssDest = './themes/zurb_foundation/css';
gulp.task('styles', function(){
gulp.src(sassFiles)
.pipe(sourcemaps.init())
.pipe(autoprefixer())
.pipe(gulp.dest(cssDest))
.pipe(sass({outputStyle: 'expanded'}).on('error', sass.logError))
.pipe(gulp.dest(cssDest))
.pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
.pipe(rename({ extname: 'min.css' }))
.pipe(sourcemaps.write('./themes/zurb_foundation/css'))
.pipe(gulp.dest(cssDest))
});
gulp.task('watch', function() {
livereload.listen();
gulp.watch(sassFiles, ['styles']);
})
I've finally gotten it to produce the following error:
CssSyntaxError: /Users/USERNAME/Desktop/SITEFOLDER/ROOTDIR/themes/zurb_foundation/scss/foundation.scss:1:1: Unknown word
You tried to parse SCSS with the standard CSS parser; try again with the
postcss-scss parser> 1 | // Foundation by ZURB
I guess at this point, my question would be how should I set-up my gulpfile to tackle the postcss-scss parsing?
So first of all we declare the necessary packages as const as these values shouldn't change their assignation.
const gulp = require('gulp');
const sass = require('gulp-sass');
const sourcemaps = require('gulp-sourcemaps');
const cssmin = require('gulp-cssmin');
Then we write a gulp task called sass, in which we search for all files in the styles folder in an .scss format.
We check and log any errors, we create sourcemaps which allow the browser to map CSS generated by SASS back to the original source file (if you want to use your .scss/.css that way).
We then write your new .css files to the public/styles folder.
gulp.task('sass', function () {
return gulp.src('./styles/*.scss')
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(sourcemaps.write('./maps'))
.pipe(gulp.dest('./public/styles'));
});
After which, we write a second gulp task called minify-css.
We look for all files in the .css format inside our styles folder.
First of all we auto prefix all our css properties. For example, if you have a css class where you have set:
user-select: none;
Autoprefixing will handle adding:
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
After which we minify, concatenate and then name our new minified css file as main.min.css and then save it in the public/styles folder.
gulp.task('minify-css', function(){
gulp.src(['./styles/*.css'])
.pipe(autoprefixer({
browsers: ['last 2 versions']
}))
.pipe(cssmin())
.pipe(concat('main.css'))
.pipe(rename("main.min.css"))
.pipe(gulp.dest('./public/styles'));
});
We then write a task called build, so to call both the sass and minify-css tasks in chronological order by simply running gulp build in the terminal.
gulp.task('build', [‘sass’, ‘minify-css’]);

How do I use post-css to autoprefix SCSS without compiling to CSS?

I have a static site that is generated using Jekyll.
Directory structure:
| _sass/
|---| subfolder/
|---|---| _component-1.scss
|---|---| _component-2.scss etc
| css/
|---| main.scss
| _site/
|---| css/
|---|---| main.css
main.scss imports all my SCSS components into one file, and Jekyll compiles the SCSS into the 'source' directory (where the static site is generated) - _site.
I want to use an autoprefixer on my SCSS components. There are Jekyll plugins that do this, however I host the site on GitHub pages, which disables plugins for security reasons. I could use the plugin locally and then just push the _site directory to GitHub, but I don't want to use this option.
I want to use a Gulp task to autoprefix my SCSS components, without first compiling the SCSS to CSS. I want to simply autoprefix in my Gulp build step, and let the Jekyll build process take care of the SCSS compilation.
So I've changed the sass_dir in the Jekyll _config.yml file to be _gulped-sass (or whatever) instead of _sass, and tried the following gulp task:
var gulp = require('gulp');
var autoprefixer = require('gulp-autoprefixer');
var source = '_sass/**/*.scss';
var destination = '_gulped-sass';
gulp.task('autoprefixer', function() {
gulp.src(source)
.pipe(autoprefixer({
browsers: ['last 2 versions']
}))
.pipe(gulp.dest(destination));
});
..however this gives the error:
$ gulp autoprefixer
$ error: you tried to parse SCSS with the standard CSS parser; try again with the postcss-scss parser
Ok, so the docs for post-scss gives the useage as
var syntax = require('postcss-scss');
postcss(plugins).process(scss, { syntax: syntax }).then(function(result) {
result.content // SCSS with transformations
});
..and the docs for post-css give the useage as:
gulp.task('css', function () {
var postcss = require('gulp-postcss');
var sourcemaps = require('gulp-sourcemaps');
return gulp.src('src/**/*.css')
.pipe( sourcemaps.init() )
.pipe( postcss([ require('precss'), require('autoprefixer') ]) )
.pipe( sourcemaps.write('.') )
.pipe( gulp.dest('build/') );
});
I cannot work out from the docs how to use the postcss-scss parser in my Gulp task. I've tried many different combinations of the two examples from the docs, but none work.
So, how can I use post-css and/or post-scss in my Gulp task in order to autoprefix my SCSS without compiling it to CSS?
Figured it out. The post-scss parser (not plugin) can be assigned as the syntax property of an object passed as a second parameter to the postcss function. It starts to look really messy, but it works:
var gulp = require('gulp');
var source = '_sass/**/*.scss';
var destination = '_gulped-sass';
var postcss = require('gulp-postcss');
var autoprefixer = require('autoprefixer');
gulp.task('autoprefixer', function () {
return gulp.src(source)
.pipe(postcss([autoprefixer({
browsers: ['last 2 versions']
})], {
syntax: require('postcss-scss')
}))
.pipe(gulp.dest(destination));
});

How to configure gulp-sass properly?

Here is my gulpfile.
var gulp = require('gulp');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var babel = require("gulp-babel");
// Gulp Sass Task
gulp.task('sass', function () {
console.log('called');
// gulp.src locates the source files for the process.
// This globbing function tells gulp to use all files
// ending with .scss or .sass within the scss folder.
gulp.src("scss/*.scss")
// Converts Sass into CSS with Gulp Sass
.pipe(sass().on('error', sass.logError))
// Outputs CSS files in the css folder
.pipe(gulp.dest("css"));
});
// Watch scss folder for changes
gulp.task('watch', function() {
// Watches the scss folder for all .scss and .sass files
// If any file changes, run the sass task
gulp.watch('./scss/**/*.{scss,sass}', ['sass'])
});
gulp.task("transpile", function () {
return gulp.src("js/*.js")
.pipe(babel())
.pipe(gulp.dest("./compile"));
});
// Creating a default task
gulp.task('build', ['sass', 'transpile']);
gulp sass runs successfully but does not create any css folder which I am expecting. Also when I run the sass manually,
sass --trace _picker.scss:css/_picker.css
I see the css being compiled properly. Not sure what is going wrong with gulpfile. Any help would be really appreciated.

gulp-sass: ERROR - file to import not found or unreadable

I am having problems getting my SASS files to compile having now split them out and importing ones I require in my main scss file.
I have a styles folder that contains:
main.scss
top_menu.scss
I have added some imports to my main.scss:
#import 'font-awesome';
#import 'bootstrap';
#import 'custom_bootstrap';
#import 'top_menu';
and my gulp-sass task looks like this
gulp.task('compile_sass', ['compile_bower_sass'], function () {
return gulp.src(paths.scss_files, {base:'src'})
.pipe(gulp.dest(paths.dist))
.on('error', gutil.log)
.pipe(sass().on('error', sass.logError))
.pipe(minifycss({
keepSpecialComments: false,
removeEmpty: true
}))
.pipe(rename({suffix: '.min'}))
.pipe(gulp.dest(paths.dist))
});
The paths.scss_files variable is set to:
scss_files: './src/assets/styles/**/*.scss'
When the task runs I receive an error:
file to import not found or unreadable: top_menu
I actually want to be able to split my scss out into separate related sub folders and then use #import: 'navigation\top_menu' kinda thing.
Why would this error be coming up?
Thanks
EDIT:
The compile_bower_sass task compiles some other scss files (font-awesome, bootstrap, custom_bootstrap) which are required as you can see from the #import lines on my main.scss.
When running the compile_sass task and watching the output (dist) folder, I see the css files get generated from the compile_bower_sass task (so font-awesome.css, bootstrap.css, custom_bootstrap.min.css). I notice that the top_menu.scss file gets copied across too, but does not get compiled, so I guess this is why the error occurs.
Do I need to specify an order in my task, so could I make sure it compiles main.scss last to ensure any required files such as my custom top_menu.scss get compiled first and are available for my main file to access?
EDIT 2
OK, so I think my thoughts this was down to the order of compilation is correct.
If I change my scss_files variable to explicitly set the order they get piped to the gulp-sass (this time I have further organised into folders)
scss_files: ['./src/assets/styles/custom_bootstrap.scss',
'./src/assets/styles/navigation/top_menu.scss',
'./src/assets/styles/navigation/user_toolbar.scss',
'./src/assets/styles/main.scss']
Now my original compile-sass task works as is.
So, my next question is how do I configure gulp-sass so that I can ensure my main.scss file is compiled last? Or am I going about this all the wrong way?
EDIT 3:
I should probably have added these extra task configs when first asking this question. So the compile_sass task requires compile_bower_sass to be run first.
/*-BOWER PACKAGEs INCLUSION --------------------------------------------*/
gulp.task('compile_bower_sass', ['compile_bower_css'], function(){
var sassFiles = mainBowerFiles('**/*.scss');
return gulp.src(sassFiles)
.pipe(rename(function(path){
path.basename = path.basename.replace(/^_/, '');
return path;
// required where the string begins with _ , meaning that sass won't compile it (bootstrap)
}))
.pipe(sass({onError: function(e) { console.log(e); } }))
.pipe(gulp.dest(paths.dist_styles));
});
gulp.task('compile_bower_css', function(){
var cssFiles = mainBowerFiles('**/*.css');
return gulp.src(cssFiles)
.pipe(gulp.dest(paths.dist_styles));
});
gulp.task('compile_sass', ['compile_bower_sass'], function () {
return gulp.src(paths.scss_files, {base:'src'})
.pipe(sass({outputStyle: 'compressed'})
.on('error', sass.logError))
.pipe(rename({suffix: '.min'}))
.pipe(gulp.dest(paths.dist))
});
Im now ending up with
file to import not found or unreadable: font-awesome
In my dist style folder I can see font-awesome.css has been generated. I am pretty new at gulp and sass compilation, so no doubt I have misunderstood something here.
When the #import statement is used, is the file looking for that named scss or css file?
I have been having the same issue (using a mac with Sierra) and it seemed to only happen when I was using the glob style of including.
It turns out it is due to a race condition, you can work around it by putting a short wait in like so...
var gulp = require('gulp');
var sass = require('gulp-sass');
var wait = require('gulp-wait');
gulp.task('scss', function () {
gulp.src('resources/scss/**/*.scss')
.pipe(wait(200))
.pipe(sass())
.pipe(gulp.dest('public/dist'));
});
Add line breaks between the #import lines.
I tried many other solutions, some suggested it's a SublimeText issue having to do with setting "atomic_save": true, that didn't work for me.
I even tried adding a .pipe(wait(500)). Didn't work either.
Then I just added a line break before the offending #import. So in your case if it's throwing an error regarding top_menu, put a line break so it becomes:
#import 'custom_bootstrap';
#import 'top_menu';
I have no idea why, but this is the only thing that worked for me.
As best-practice I would add line breaks between all the lines just in case.
I've tried to recreate the issue you're having, but for me it seems to run fine.
I'll attach my code, and a shot of the folder structure to compare.
The only omission is the ['compile_bower_sass'] part, as I'm not totally sure what you need here. Is it possible that's something that should be using a loadPath instead?
You'll also notice from the screenshot of the folders that your scss files are getting copied over to dist as well. This may not be desirable.
Here's the Gulp code:
var gulp = require('gulp');
var sass = require('gulp-sass');
var minifycss = require('gulp-minify-css');
var rename = require('gulp-rename');
var gutil = require('gulp-util');
var paths = {
scss_files: './src/assets/styles/**/*.scss',
dist: './dist'
};
gulp.task('compile_sass', function () {
return gulp.src(paths.scss_files, {base:'src'})
.pipe(gulp.dest(paths.dist))
.on('error', gutil.log)
.pipe(sass().on('error', sass.logError))
.pipe(minifycss({
keepSpecialComments: false,
removeEmpty: true
}))
.pipe(rename({suffix: '.min'}))
.pipe(gulp.dest(paths.dist))
});
Here's the folders:
http://take.ms/AOFND
Perhaps all you need is:
var gulp = require('gulp');
var sass = require('gulp-sass');
var rename = require('gulp-rename');
var paths = {
scss_files: './src/assets/styles/**/*.scss',
dist: './dist'
};
gulp.task('compile_sass', function () {
return gulp.src(paths.scss_files, {base:'src'})
.pipe(sass({outputStyle: 'compressed'})
.on('error', sass.logError))
.pipe(rename({suffix: '.min'}))
.pipe(gulp.dest(paths.dist))
});
I was getting the error trying to migrate from Gulp 3.9.1 to 4.0.2, which requires a different way of setting up the gulpfile.js. I tried the line breaks in my file and also the wait just incase it was a race condition.
Utilizing gulp-plumber, it took away the error and my compiling of sass was successful.
function compile_sass() {
return gulp
.src('./wwwroot/css/**/*.scss')
.pipe(plumber())
.pipe(sass())
.pipe(gulp.dest("./wwwroot/css"));
}
The important part was the
.pipe(plumber())

Libsass with Susy not working + Gulp

I've no doubt others have got this working... I just haven't quite worked out how right now.
Gulp
var gulp = require('gulp');
var sass = require('gulp-sass');
var handleErrors = require('../util/handleErrors');
var sourcemaps = require('gulp-sourcemaps');
var minifyCSS = require('gulp-minify-css');
gulp.task('sass', function () {
return gulp.src('./frontend/sass/style.scss')
.pipe(sourcemaps.init())
.pipe(sass({
'require':'susy'
}))
//.pipe(minifyCSS())
.pipe(sourcemaps.write('./app/www/css'))
.on('error', handleErrors)
.pipe(gulp.dest('./app/www/css'))
});
Sass
#import "susy";
Gulp Running
[23:58:08] Starting 'sass'...
stream.js:94
throw er; // Unhandled stream error in pipe.
^
Error: file to import not found or unreadable: susy
Current dir: C:/var/www/rnli.hutber.com/frontend/sass/
I have installed susy#2.2.2 in the root along side the gulp file with the following: gem install susy
Current working setup with gulp-ruby-sass
I do however have it working, which confirms that susy is working via the gem installed with the following code:
var gulp = require('gulp');
var sass = require('gulp-ruby-sass');
var handleErrors = require('../util/handleErrors');
var minifyCSS = require('gulp-minify-css');
gulp.task('sass', function () {
return gulp.src('./frontend/sass/style.scss')
.pipe(sass({
'sourcemapPath':'./app/www/css',
'require':'susy'
}))
//.pipe(minifyCSS())
.on('error', handleErrors)
.pipe(gulp.dest('./'))
});
NOTE The above code will not working using gulp-ruby-sass#1.0.0alpha' It will only work as I can tell withv0.7.1`
package.json
"devDependencies": {
"gulp": "~3.8.10",
"gulp-sass": "~1.3.2",
"gulp-ruby-sass": "~0.7.1",
"gulp-sourcemaps": "~1.3.0",
"susy":"~2.2.1"
}
How do I get susy working correctly and able to compile into css?
I've managed to get susy working with libsass (gulp-sass)
gulp-sass needs to know where to find files specified with an #import directive. You can try set the includesPath option in gulp-sass to point to your local copy of susy.
As I've installed susy with bower, I have something like this:
var sass = require('gulp-sass');
gulp.task('sass', function () {
return gulp.src(config.src)
.pipe(sass({
includePaths: [
'bower_components/susy/sass'
]
}))
...
});
I had the same issue, but with Grunt instead of Gulp.
You could do is use the full path for susy.
First find out where your gems are installed (gem env, and look up for GEM PATHS; in my case they where in /Library/Ruby/Gems/2.0.0).
And then in your style.scss file instead of #import susy you do:
#import "/Library/Ruby/Gems/2.0.0/gems/susy-2.2.2/sass/susy";
(Replace 2.2.2 for your version of susy, but if you are going to use libsass you should use something quite up to date; and you'll have to change that line when you upgrade...)
Not as elegant, but a small price to pay to use libsass.
Update: If you put includePaths: ['/Library/Ruby/Gems/2.0.0/gems/susy-2.2.2/sass'] in your Gulp task you can get away with just "#import susy;", although you just moved the untidyness somewhere else.
It's probably neater to do it with Bower, as explained in another answer down here, and to have a local susy install for the project; but since I'm not using bower yet (shame on me), I just use a global susy copy for all my projects.

Resources