Gulp is compiling every Js-file - javascript

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

Related

Including bootstrap js with gulp causing errors

I have successfully got all my scss including bootstraps to combine into one minified file using gulp. Now I am trying to do the same with my js and bootstraps. The problem is that uglify keeps throwing errors at me like Unexpected token: name ($) etc. And won't minify / compile bootstrap js because of this. Now I'm starting to believe I am going the wrong way about this.
This is my file structure:
app/js(my.js files in here)/vendor/bootstrap/js/src/(boostrap js files here)
As you can see, what I have done is just copy the bootstrap js files into my files in the hope that they would be minified / compiled along with mine. But with the scss I imported the files like you usually do. So am I doing this the wrong way?
here's my gulp.js code
var gulp = require('gulp');
var sass = require('gulp-sass');
var cleanCss = require('gulp-clean-css');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
var gulpSequence = require('gulp-sequence');
var autoPrefixer = require('gulp-autoprefixer');
var concat = require('gulp-concat');
var jshint = require('gulp-jshint');
var csslint = require('gulp-csslint');
var htmlReporter = require('gulp-csslint-report');
var plumber = require('gulp-plumber');
var sourcemaps = require('gulp-sourcemaps');
//plumber error
var onError = function (err) {
console.log(err);
};
//create sourcemaps, convert scss to css, lint check, minify and prefix
gulp.task('css', function(){
return gulp.src('app/scss/**/*.scss')
.pipe(plumber({
errorHandler: onError
}))
.pipe(sourcemaps.init())
.pipe(sass())
.pipe(csslint())
.pipe(htmlReporter())
.pipe(cleanCss())
.pipe(rename({
suffix: '.min'
}))
.pipe(autoPrefixer({
browsers: ['last 3 versions'],
cascade: false
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('dist/css'))
});
//create sourcemaps, lint check, compile into one file, minify
gulp.task('js', function() {
return gulp.src('app/js/**/*.js')
.pipe(plumber({
errorHandler: onError
}))
.pipe(sourcemaps.init())
.pipe(jshint())
.pipe(jshint.reporter('gulp-jshint-html-reporter', {
filename: __dirname + '/jshint-output.html',
createMissingFolders : false
}))
.pipe(concat('all.js'))
.pipe(uglify())
.pipe(rename({
suffix: '.min'
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('dist/js'))
});
//copy php files to app
gulp.task('phpCopy', function(){
return gulp.src('app/*.php')
.pipe(plumber({
errorHandler: onError
}))
.pipe(gulp.dest('dist'));
});
//functions to run on file save
gulp.task('watch', function(){
gulp.watch('app/scss/**/*.scss', ['css']);
gulp.watch('app/*.php', ['phpCopy']);
gulp.watch('app/js/**/*.js', ['js']);
});
gulp.task('default', ['css', 'js', 'phpCopy']);
To any body struggling with this here is what I did to fix this problem.
//create sourcemaps, lint check, compile into one file, minify
gulp.task('js', function() {
return gulp.src([
'node_modules/jquery/dist/jquery.js',
'node_modules/bootstrap/dist/js/bootstrap.js',
'app/js/**/*.js'
])
.pipe(plumber({
errorHandler: onError
}))
.pipe(sourcemaps.init())
.pipe(jshint())
.pipe(jshint.reporter('gulp-jshint-html-reporter', {
filename: __dirname + '/jshint-output.html',
createMissingFolders : false
}))
.pipe(concat('all.js'))
.pipe(uglify())
.pipe(rename({
suffix: '.min'
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('dist/js'))
});
I had to point to the bootstrap file inside node_modules instead of copying them into my files. Here's a tutorial that helped me http://george.webb.uno/posts/gulp-and-npm-for-front-end-web-development
And if you copy this code be aware that sourcemaps isn't working properly yet. I will continue to work on this.

Node - An #import loop has been found

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.

gulp livereload not working

I have this weird problem after installing the following gulp packages. Everything renders just fine, but when it gets to the part of the liveReload() it just doesn't reload the page...
I installed the livereload chrome extension (is it necessary?), and it seems like there is nothing to config there...
Here is my gulpfile:
var gulp = require('gulp'),
autoPrefixer = require('gulp-autoprefixer'),
jade = require('gulp-jade'),
liveReload = require('gulp-livereload'),
sourceMaps = require('gulp-sourcemaps'),
ts = require('gulp-typescript'),
tsLint = require('gulp-tslint'),
watch = require('gulp-watch'),
sass = require('gulp-sass');
// Configuration
var config = {
js: 'public/_assets/frontend/js',
css: 'public/_assets/frontend/css',
fonts: 'public/_assets/frontend/fonts',
images: 'public/_assets/frontend/img',
markup: 'public/'
};
// Javascript
gulp.task('scripts', function() {
var tsResult = gulp.src(['src/ts/*.ts', 'src/ts/**/*.ts'])
.pipe(tsLint())
.pipe(ts({
noImplicitAny: true
}));
tsResult.js
.pipe(gulp.dest(config.js))
.pipe(liveReload());
});
// Sass
gulp.task('sass', function() {
return gulp.src(['src/sass/*.scss', 'src/sass/**/*.scss'])
.pipe(watch(['src/sass/*.scss', 'src/sass/**/*.scss']))
.pipe(sourceMaps.init())
.pipe(sass.sync().on('error', sass.logError))
.pipe(autoPrefixer({
browsers: ['last 3 versions'],
cascade: false
}))
.pipe(sourceMaps.write())
.pipe(gulp.dest(config.css))
.pipe(liveReload());
});
// jade
gulp.task('markup', function() {
return gulp.src(['src/**/*.jade', 'src/**/_*.jade'])
.pipe(jade({
pretty: true
}))
.pipe(gulp.dest(config.markup))
.pipe(liveReload());
});
// Images
gulp.task('images', function() {
return gulp.src(['src/images/**/*.*', 'src/images/*.*'])
.pipe(gulp.dest(config.images));
});
// Watch
gulp.task('watch', function() {
liveReload.listen();
gulp.watch(['src/ts/*.ts', 'src/ts/**/*.ts'], ['scripts']);
gulp.watch(['src/sass/*.scss', 'src/sass/**/*.scss'], ['sass']);
gulp.watch(['src/*.jade', 'src/**/*.jade'], ['markup']);
});
// Default Task
gulp.task('default', function() {
gulp.start('sass', 'scripts', 'markup', 'images', 'watch');
});
Everything works just fine, the gulp is doing it's thing and rendering all my files, but the page won't reload... I'm using python simple http server on port 8000.
Any ideas?
The only thing that comes to my mind is: did you include the livereload client script into your page? AFAIK you should be supposed to inject this script at the end of your page's body.
<script src="http://localhost:35729/livereload.js"></script>
You can use
Live Reload Browser Page
GitHub
Live Reload Browser Page is very flexible tool for live reloading of the browser page.

Cannot use vinylPaths del with gulp

I have the following gulp task, basically what it does is:
compile all .styl files
put the result in theme/app folder
minify all file in theme/app folder
concatenate all file in folder theme/app folder to a single file
add some license information to the file
save result in foldertheme
delete all files in theme/app folder
I cannot make work the last step, I need to delete all files in theme/app.
I have not specific error, what could could be wrong in my script and how to solve it?
gulp.task('_release-theme:compile', function () {
gulp.src([
'app/**/*.styl',
'!app/**/**mixins**.styl',
'!app/**/**variables**.styl',
])
.pipe(stylus({
compress: false,
use: nib()
}))
.pipe(gulp.dest('theme/app'))
.pipe(cleanCSS())
.pipe(concat('theme.css'))
.pipe(header(fs.readFileSync('licenses/app.txt', 'utf8')))
.pipe(gulp.dest('theme/'))
.pipe(vinylPaths(del['theme/app/**/*'])); // problem here
});
del is a function. Your object property access del['theme/app/**/*'] makes no sense here.
Instead listen for the end event in your stream and then delete the files using rimraf:
var rimraf = require('rimraf');
gulp.task('_release-theme:compile', function (done) {
gulp.src([
'app/**/*.styl',
'!app/**/**mixins**.styl',
'!app/**/**variables**.styl',
])
.pipe(stylus({
compress: false,
use: nib()
}))
.pipe(gulp.dest('theme/app'))
.pipe(cleanCSS())
.pipe(concat('theme.css'))
.pipe(header(fs.readFileSync('licenses/app.txt', 'utf8')))
.pipe(gulp.dest('theme/'))
.on('end', function() {
rimraf('theme/app/**/*', done);
});
});

Concatenated files put into main.js just keeps stacking instead of clearing the file then adding the code

I'm trying to compile all my scripts into a single main.js file which I can then link to my index file. Problem is that all my script files are being concatenated and then just added to the main.js file, so if I save 3 times, I will basically have 3 copies of all my scripts concatenated and put in the main.js file.
I would like to either delete the main.js file each time I save and then run the concatenation, or just clean the file before adding the contents. Now if I try to delete the file using the del module, I receive an error stating that I can't delete files out of the working directory without forcing this action. I would like to avoid forcing this if possible.
I feel that there must be a more elegant way of doing this..
Here's my script task:
// Concat and compile our JS into a minified dist file
gulp.task('scripts', function() {
return gulp.src('../app/public/assets/scripts/**/*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(concat('main.js'))
//.pipe(del(['../app/public/assets/scripts/main.js'])) <-- Doesn't work without forcing
.pipe(gulp.dest('../app/public/assets/scripts'))
.pipe(gulpif(flags.build, gulp.dest('../app/dist/assets/scripts')))
.pipe(rename({ suffix: '.min' }))
.pipe(uglify())
.pipe(gulpif(flags.build, gulp.dest('../app/dist/assets/scripts')))
.pipe(notify({ message: 'Finished compiling scripts' }));
});
I usually do something like this (very simplified :) ):
var PARAMS = {
destPath: 'build',
js: [
'src/js/test1.js',
'src/js/test2.js',
// ecc...
],
// other
};
var TARGETS = {
dest: 'main.js', // dest file
extra: [
// This files are inclued only in .bundle.min.js version
// extra file here
],
js: [
'src/js/test1.js',
'src/js/test2.js',
// ecc...
]
};
gulp.task('connect', function() {
return connect.server({
livereload: true,
host: '0.0.0.0',
port: 8000
});
});
gulp.task('reload', ['build'], function () {
return gulp.src(['sandbox/**/*.html'])
.pipe(connect.reload());
});
gulp.task('watch', ['connect', 'build'], function () {
var src = [];
// other
src = src.concat(PARAMS.js);
return gulp.watch(src, ['reload']);
});
gulp.task('clean', function (done) {
return del(['build'], done);
});
gulp.task('build', ['clean'], function () {
return gulp.src(target.js);
.pipe(concat(target.dest))
.pipe(gulp.dest(PARAMS.destPath)) // Plain
.pipe(uglify())
.pipe(rename({ extname: '.min.js' })) // Minified
.pipe(gulp.dest(PARAMS.destPath))
.pipe(addsrc(target.extra))
.pipe(order(target.extra))
.pipe(concat(target.dest))
.pipe(rename({ extname: '.bundled.min.js' })) // Bundled
.pipe(gulp.dest(PARAMS.destPath));
});
gulp.task('default', ['build']);

Categories