I am currently setting up my gulpfile and im having a problem with gulp-sass when the watch task is running the scss task.
This is how my gulpfile.js looks:
var gulp = require('gulp'),
plumber = require('gulp-plumber'),
sass = require('gulp-sass'),
sourcemaps = require('gulp-sourcemaps');
var onError = function(err) {
console.log(err);
};
var bases = {
dist: './dist/',
src: './src/'
};
var paths = {
sass: [bases.src + 'scss/base.scss'],
sourcemaps: '/'
};
gulp.task('scss', function(){
return gulp.src(paths.sass)
.pipe(plumber({
errorHandler: onError
}))
.pipe(sourcemaps.init())
.pipe(sass({
sourcemap: true,
style: 'expanded',
sourceComments: 'normal',
onError: onError
}))
.pipe(sourcemaps.write(paths.sourcemaps))
.pipe(gulp.dest(bases.dist + 'css/'))
});
gulp.task('watch', function(){
gulp.watch(bases.src + 'scss/**/*.scss', ['scss'])
});
gulp.task('default', ['scss','watch']);
base.scss only contains this:
(also tried full path and without fileext. same result)
#import 'modules/modules_base.scss';
The error i'm getting in console:
[18:54:13] Finished 'scss' after 12 ms
[18:54:15] Starting 'scss'...
{ [Error: src\scss\base.scss
1:9 file to import not found or unreadable: ./src/scss/modules/modules_base.scss
Current dir: ]
message: 'src\\scss\\base.scss\n 1:9 file to import not found or unreadable: ./src/scss/modules/modules_base.scss\nCurrent dir: ',
column: 9,
line: 1,
file: 'stdin',
status: 1,
messageFormatted: '\u001b[4msrc\\scss\\base.scss\u001b[24m\n\u001b[90m 1:9\u001b[39m file to import not found or unreadable: ./src/scss/modules/modules_base.scss\nCurrent dir: ',
name: 'Error',
stack: 'Error: src\\scss\\base.scss\n 1:9 file to import not found or unreadable: ./src/scss/modules/modules_base.scss\nCurrent dir: \n at options.error (c:\\Code\\colorpicker\\node_modules\\gu
lp-sass\\node_modules\\node-sass\\lib\\index.js:276:32)',
showStack: false,
showProperties: true,
plugin: 'gulp-sass' }
The basic error is: 1:9 File to import not found or unreadable: ./src/scss/modules/modules_base.scss
the structure of the app:
-component
gulpfile.js
-dist
-css
base.css
base.css.map
-src
-scss
base.scss
-modules
-modules_base.scss
The error only happens when i save the modules_base.scss and the watch task is fired, and never when im running the default task.
all suggestions are appreciated!
Notes:
Node -v : 0.12.0
Gulp: 3.8.11
gulp-sass: 2.0.1
Are you using vscode? I found this on github
gulp.task('sass', function () {
return gulp.src(SCSS_SRC)
.pipe(wait(500))
.pipe(sass({
outputStyle: 'compressed',
includePaths: ['./bower_components/susy/sass', './bower_components/breakpoint-sass/stylesheets']
}).on('error', sass.logError))
.pipe(concat('style.css'))
.pipe(autoprefixer({
browsers: ['>1%', 'last 2 versions'],
cascade: false
}))
.pipe(gulp.dest('./dist/css'));
});
Basically
I was having this issue when saving in sublime. The first time the
file changed, gulp watch would fire before the file either completed
saving, or was unreadable when lib-sass started. I added a 50ms delay
to the pipe which seems to work.
Have you tried this?
edit - I use run-sequence to ensure processes finish before running things that require them. Check it out
gulp.task('default',function(callback){
runSequence('clean-folder','css','js'['responsive-jpg','responsive-webp','copy-data']),callback
});
Basically clean-folder runs and deletes stuff I want a redo on, then css compiles. Nothing after will run until run-sequence gets the callback that all of the scss has been transpiled.
Related
i have a problem with my gulp.
Its works fine and its really fast but Gulp is compiling all js files in my project...
my gulp-watch:
gulp.task('watch', function () {
gulp.watch(sassFilesWatch, ['styles']);
gulp.watch(jsFilesWatch, ['uglify'])
});
My array:
var jsFilesWatch = [
'clients/*/template/lib/jscripts/*.js',
'clients/*/template/modules/**/*.js',
'system/lib/jscripts/*.js',
'system/mod/**/*.js',
'clients/core/modules/**/*.js',
'!/**/*.min.js'
];
Thats my function:
gulp.task('uglify', function(){
pump([
gulp.src(jsFilesWatch, {
base: './'
}),
debug({
title: 'Compiled',
showFiles: false,
}),
uglify(),
rename({ suffix: '.min' }),
gulp.dest('./')
]);
});
And thats the output:
Output
Just my saved file should be compiled
how can i do that?
thanks alot
It seems all your files with .js extensions are
being debugged, uglified and minified.
Which saved file are you trying to compile?
**/*.js uses the gulp command to watch all files with the .js extension in all folders.
You could use .pipe()
var uglify = require('gulp-uglify'),
concat = require('gulp-concat');
gulp.task('js', function() {
gulp.src('scripts/*.js')
.pipe(uglify())
.pipe(concat('script.js'))
.pipe(gulp.dest('assets'))
});
Have a look into this Plugin, That will solve your problem
https://www.npmjs.com/package/gulp-changed
Try Changing your task to,
gulp.task('uglify', function(){
pump([
gulp.src(jsFilesWatch, {
base: './'
}),
changed('dist'),
ngAnnotate(),
debug({
title: 'Compiled',
showFiles: false,
}),
uglify(),
rename({ suffix: '.min' }),
gulp.dest('./')
]);
});
Note: this might run all your .js files at first time after you run your task, but it will identify the changed file on subsequent runs
I'm new with js, node and all things related.
I'm trying to set up a front end development environment from scratch, using gulp, bower, browser sync, and other plugins.
I'm almost done, it's working in some way, except for a couple of details I can't resolve because I'm not sure if it's something in the code syntax or the order of the functions executed in my gulpfile.js file, or because the plugins are not being used correctly. I have already tried to change the order of them, change some path, etc with no results.
Now I'm experiencing the following issues:
The main.scss needs to be saved two times before see the changes reflected in the browser.
When I run gulp in the console this is what I receive (these errors are new and appeared after a minor change proposed by Poeta in his answer, which helped me a lot.
[16:38:08] Starting 'html'...
[16:38:08] 'html' errored after 41 ms
[16:38:08] ReferenceError: injectFiles is not defined
at Gulp. ([full_path]\gulpfile.js:50:18)
at module.exports ([full_path]\node_modules\orchestrator\lib\runTask.js:34:7)
at Gulp.Orchestrator._runTask ([full_path]\node_modules\orchestrator\index.js:273:3)
at Gulp.Orchestrator._runStep ([full_path]\node_modules\orchestrator\index.js:214:10)
at [full_path]\node_modules\orchestrator\index.js:279:18)
at finish ([full_path]\node_modules\orchestrator\lib\runTask.js:21:8)
at [full_path]\node_modules\orchestrator\lib\runTask.js:52:4
at f ([full_path]\node_modules\once\once.js:17:25)
at DestroyableTransform.onend ([full_path]\node_modules\end-of-stream\index.js:31:18)
at emitNone (events.js:91:20)
This is my gulpfile.js content:
var gulp = require('gulp');
var sass = require('gulp-sass');
var inject = require('gulp-inject');
var wiredep = require('wiredep').stream;
var plumber = require('gulp-plumber');
var imagemin = require('gulp-imagemin');
var browserSync = require('browser-sync');
var uglify = require('gulp-uglify');
gulp.task('styles', function(){
var injectAppFiles = gulp.src(['!src/styles/main.scss', 'src/styles/*.scss'], {read: false});
var injectGlobalFiles = gulp.src('src/global/*.scss', {read: false});
function transformFilepath(filepath) {
return '#import "' + filepath + '";';
}
var injectAppOptions = {
transform: transformFilepath,
starttag: '// inject:app',
endtag: '// endinject',
addRootSlash: false
};
var injectGlobalOptions = {
transform: transformFilepath,
starttag: '// inject:global',
endtag: '// endinject',
addRootSlash: false
};
return gulp.src('src/styles/main.scss')
.pipe(plumber())
.pipe(wiredep())
.pipe(inject(injectGlobalFiles, injectGlobalOptions))
.pipe(inject(injectAppFiles, injectAppOptions))
.pipe(sass())
.pipe(gulp.dest('dist/styles'));
});
gulp.task('html', ['styles'], function(){
var injectAppFiles = gulp.src('src/styles/*.scss', {read: false});
var injectOptions = {
addRootSlash: false,
ignorePath: ['src', 'dist']
};
return gulp.src('src/index.html')
.pipe(plumber())
.pipe(inject(injectFiles, injectOptions))
.pipe(gulp.dest('dist'));
});
gulp.task('imagemin', function() {
gulp.src('src/assets/*.{jpg,jpeg,png,gif,svg}')
.pipe(plumber())
.pipe(imagemin())
.pipe(gulp.dest('dist/assets'));
});
gulp.task('uglify', function() {
gulp.src('src/js/*.js')
.pipe(uglify())
.pipe(gulp.dest('dist/js'));
});
gulp.task('sass', function() {
gulp.src('src/styles/*.scss')
.pipe(plumber())
.pipe(sass())
.pipe(gulp.dest('dist/styles/'));
});
gulp.task('browser-sync', function() {
browserSync.init(["styles/*.css", "js/*.js","index.html"], {
server: {
baseDir: "dist"
}
});
});
gulp.task('watch', function() {
gulp.watch('src/js/*.js', ['uglify']).on('change', browserSync.reload);
gulp.watch('src/styles/*.scss', ['sass']).on('change', browserSync.reload);
gulp.watch('src/assets/*.{jpg,jpeg,png,gif,svg}', ['imagemin']).on('change', browserSync.reload);
gulp.watch('src/index.html', ['html']).on('change', browserSync.reload);
});
gulp.task('default', ['html', 'sass','imagemin', 'uglify', 'browser-sync', 'watch']);
So, could you please point me in the right direction to get this enviroment set in the proper way?
Update about previous problem: The following was resolved thanks to Bruno Poeta's answer.
Plumber found unhandled error: Error in plugin 'gulp-sass'
Message: src\styles\main.scss
Error: An #import loop has been found: (full_path)/src/styles/main.scss imports src/styles/main.scss on line 526 of src/styles/main.scss
After that message...
[15:11:18] Finished 'styles' after 4.48 s
[15:11:18] Starting 'html'...
[15:11:19] gulp-inject 1 files into index.html.
[15:11:19] Finished 'html' after 1.44 s
[15:11:19] Starting 'default'...
[15:11:19] Finished 'default' after 6.98 μs
[Browsersync] Access URLs:
Local: localhost : 3000
External: 192.168 .0.4 :3000
UI: localhost :3001
UI External: 192.168 .0.4 :3001
[Browsersync] Serving files from: dist
[Browsersync] Watching files...
Note: the line 526 doesn't exist since it is generated by the gulp-inject plugin. These are the last lines in the main.css file, line 520 and 521:
// inject:app
// endinject
The error as you may have noticed is in your styles task. The problem is that you are importing all .scss files, including main.scss itself. That is your loop, right there. Remove main.scss from the files that should be injected, like this:
gulp.task('styles', function(){
var injectAppFiles = gulp.src(['!src/styles/main.scss', 'src/styles/*.scss'], {read: false});
// ...
It should work right now.
I have 2 tasks:
whitelabel - I have a gulp task that copies a given whitelabel project into a folder
sass - compile the sass project within that folder
My problem is that when I put them to run in sequence on my default task the css the files are copied but the sass task doesnt generated the css it is suposed to. But, if i run one task than the other the css file is generated.
What am I missing?
Whitelabel Task
gulp.task('whitelabel', function() {
var argv = yargs.argv;
if (argv.whitelabel){
gulp.src('./whitelabels/_template/**/*')
.pipe(gulp.dest('./assets'));
return gulp.src('./whitelabels/'+ argv.whitelabel +'/**/*')
.pipe(gulp.dest('.'));
} else {
return gulp.src('./whitelabels/_template/**/*')
.pipe(del.sync(['./assets/']))
.pipe(gulp.dest('.'));
}
});
SASS Task
gulp.task('sass', function() {
return gulp.src('assets/styles/style.scss')
.pipe($.sourcemaps.init())
.pipe($.sass({
style: 'expanded'
}))
.on('error', $.notify.onError({
title: 'SASS Failed',
message: 'Error(s) occurred during compile!'
}))
.pipe($.sourcemaps.write())
.pipe(gulp.dest('assets/styles'))
.pipe(reload({
stream: true
}))
.pipe($.notify({
message: 'Styles task complete'
}));
});
Default Task
gulp.task('default', ['config', 'browser-sync', 'whitelabel', 'sass', 'minify-css'], function() {
gulp.watch('whitelabels/_template/assets/styles/*.css', function(file) {
if (file.type === "changed") {
reload(file.path);
}
});
gulp.watch(['*.html', 'app/**/*.html', 'views/*.html'], ['bs-reload']);
gulp.watch(['whitelabels/_template/assets/js/*.js'], ['whitelabel','bs-reload']);
gulp.watch(['app/*.js'], ['bs-reload']);
gulp.watch('whitelabels/_template/assets/styles/**/*.scss', ['whitelabel', 'sass', 'minify-css']);
});
Your original default task does not guarantee that the tasks are run in any specific order - in fact they run in parallel.
Many people use run-sequence https://www.npmjs.com/package/run-sequence to run tasks in a specified order.
Or you could make the 'whitelabel' task a dependency of the sass task by
gulp.task('sass', ['whitelabel'], function() {
This is the content of my gulpfile.js:
var gulp = require('gulp');
var bundler = require('aurelia-bundler');
var config = {
force: true,
packagePath: '.',
bundles: {
"dist/app-build": {
includes: [
'Main.js',
],
excludes:[
"gulpfile.js",
],
options: {
inject: true,
minify: true
}
},
"dist/aurelia": {
includes: [
'aurelia-bootstrapper',
'aurelia-fetch-client',
'aurelia-router',
'aurelia-animator-css',
'github:aurelia/templating-binding',
'github:aurelia/templating-resources',
'github:aurelia/templating-router',
'github:aurelia/loader-default',
'github:aurelia/history-browser',
'github:aurelia/logging-console'
],
options: {
inject: true,
minify: true
}
}
}
};
gulp.task('bundle', function() {
console.log("ok");
return bundler.bundle(config);
});
When I run gulp bundle the following error occurs:
[08:08:54] 'bundle' errored after 536 ms [08:08:54] Error on fetch for
gulp.js at file:///C:/myapp/gulp.js
Loading gulpfile.js
Error: ENOENT: no such file or directory, open 'C:\myapp\gulp.js'
at Error (native)
I wounder why he is searching for gulp.js in the root Directory of the project and not inside the node_modules folder?
The first thing this file does is attempt to require 'gulp' - have you done an npm install first?
Finally I got the problem solved by deleting the node_modules folder and running npm install again
I've been trying to improve my standard gulpfile to notify when errors occur when compiling scss and JS.
SCSS Issue
I have it working for SCSS, it throws the error in terminal, makes a noise and doesn't stop gulp running - which is great.
Strangely, my styles used to compile when I ran gulp, but now I need to save one of the .scss files to start gulp (again this is good, but I want it to compile on running gulp).
gulp
[12:07:06] Using gulpfile ~PATH/gulpfile.js
[12:07:06] Starting 'scripts'...
[12:07:06] Starting 'watch'...
[12:07:06] Finished 'watch' after 32 ms
[12:07:07] PATH/js/script-dist.js reloaded.
[12:07:07] Finished 'scripts' after 455 ms
[12:07:07] Starting 'default'...
[12:07:07] Finished 'default' after 15 μs
JS Issue
I'm also trying to notify of errors and exactly where they're coming from in for the JS too (and also prevent gulp from stopping when an error occurs). Tried adding gulp-jshint, but it doesn't seem to be working. It flags the error with a noise etc... but doesn't tell me which of the concatenated files the error is located in. It just says:
Error in plugin 'gulp-uglify'
Message:
[_PATH_]/js/script-dist.js: Unexpected token keyword «var», expected punc «{»
Details:
fileName: [_PATH_]/js/script-dist.js
lineNumber: 3
Here is my gulpfile.js
var gulp = require('gulp');
// --------------------------------------------------------------
// Plugins
// ---------------------------------------------------------------
var concat = require('gulp-concat');
var stripDebug = require('gulp-strip-debug');
var uglify = require('gulp-uglify');
var jshint = require('gulp-jshint');
var include = require('gulp-include');
var sass = require('gulp-sass');
var minifycss = require('gulp-minify-css');
var watch = require('gulp-watch');
var livereload = require('gulp-livereload');
var notify = require('gulp-notify');
var plumber = require('gulp-plumber');
// --------------------------------------------------------------
// JS
// ---------------------------------------------------------------
gulp.task('scripts', function() {
return gulp.src(['./js/script.js'])
.pipe(include())
.pipe(plumber({errorHandler: errorScripts}))
.pipe(concat('script-dist.js'))
//.pipe(stripDebug())
.pipe(jshint())
.pipe(uglify())
.pipe(gulp.dest('./js/'))
.pipe(livereload());
});
// --------------------------------------------------------------
// Styles
// ---------------------------------------------------------------
gulp.task("styles", function(){
return gulp.src("./ui/scss/styles.scss")
.pipe(include())
.pipe(plumber({errorHandler: errorStyles}))
.pipe(sass({style: "compressed", noCache: true}))
.pipe(minifycss())
.pipe(gulp.dest("./ui/css/"))
.pipe(livereload());
});
// --------------------------------------------------------------
// Errors
// ---------------------------------------------------------------
// Styles
function errorStyles(error){
notify.onError({title: "SCSS Error", message: "Check your terminal", sound: "Sosumi"})(error); //Error Notification
console.log(error.toString()); //Prints Error to Console
this.emit("end"); //End function
};
// Scripts
function errorScripts(error){
notify.onError({title: "JS Error", message: "Check your terminal", sound: "Sosumi"})(error); //Error Notification
console.log(error.toString()); //Prints Error to Console
this.emit("end"); //End function
};
// --------------------------------------------------------------
// Watch & Reload
// ---------------------------------------------------------------
gulp.task('watch', function() {
gulp.watch('./ui/scss/*.scss', ['styles']);
gulp.watch(['./js/*.js', '!./js/script-dist.js'], ['scripts']);
});
gulp.task('default', ['styles', 'watch']);
gulp.task('default', ['scripts', 'watch']);
livereload.listen();
(My JS isn't great, so please bear with me )
Update
I've now managed to plumb a JS error through to terminal, but not sure how to report what the error actually is, which file the error is coming from and which line? Obviously need to replace the console.log with some variables but not sure how to achieve this?
gulp.task('scripts', function() {
return gulp.src(['./js/script.js'])
.pipe(include())
.pipe(plumber(
//{errorHandler: errorScripts};
function() {
console.log('There was an issue compiling scripts');
this.emit('end');
}
))
.pipe(concat('script-dist.js'))
//.pipe(stripDebug())
//.pipe(jshint())
.pipe(uglify())
.pipe(gulp.dest('./js/'))
.pipe(livereload());
});
Styles not running answer:
When running you default task, your styles are not compiled, because you do this:
gulp.task('default', ['styles', 'watch']);
gulp.task('default', ['scripts', 'watch']);
Basically what you're doing here is overwriting your default task with a new one.
This can be overcome easily by combining the two:
gulp.task('default', ['scripts', 'styles', 'watch']);
Error notification in console answer:
You should do the jshinting before concatenation, or else you will get error reporing on the concatenated file (script-dist.js).
You should change your gulpfile to:
gulp.task('scripts', function() {
return gulp.src(['./js/script.js'])
.pipe(include())
.pipe(plumber(
//{errorHandler: errorScripts};
function() {
console.log('There was an issue compiling scripts');
this.emit('end');
}
))
.pipe(jshint())
.pipe(concat('script-dist.js'))
.pipe(stripDebug())
.pipe(uglify())
.pipe(gulp.dest('./js/'))
.pipe(livereload());
});
That should do the trick ;-)