gulp task can't find karma.conf.js - gulp

I am trying to run karma test via a gulp task. I use https://github.com/karma-runner/gulp-karma and for some reason gulp cannot locate my karma.conf.js. That file is located in the same folder as the gulpfile. The root of the project. No matter what path I put, I get the same error File ./karma.conf.js does not exist. I cannot figure out how to path it correctly. Here is the code for the gulp task.
gulp.task('tdd', function (done) {
new Server({
configFile: 'karma.conf.js'
}, done).start();
});

This is how I spool up karma using Gulp ( and both files are in the same root ).
var karma = require('karma');
gulp.task('karma', function (done) {
karma.server.start({
configFile: __dirname + '/karma.conf.js'
}, done);
});
UPDATE
If you are running NODE.js then
NODE Explnation for __dirname link
"The name of the directory that the currently executing script resides in."
If you are not running NODE.js, then perhaps all you needed was
configFile: '/karma.conf.js'
But if you are running NODE then use the first example.

If another destination directory is assigned to __dirname, then it doesn't work.
Try this:
var Server = require('karma').Server
gulp.task('test', function (done) {
new Server({
configFile: require('path').resolve('karma.conf.js'),
singleRun: true
}, done).start();
});

Related

GULP - How to use gulp in production /deployment?

I have not much experience with gulp and wonder what to do when deploying? How do I exclude certain tasks (like my 'sass' task for example) when deploying or how does gulp work for production - what would I do? I'm not sure if I use the wrong words or just don't understand it, but I couldn't find much online so far.
My gulp file:
var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();
var cleanCSS = require('gulp-clean-css');
var rename = require("gulp-rename");
var uglify = require('gulp-uglify');
// Compiles SCSS files from /scss into /css
gulp.task('sass', function() {
return gulp.src('scss/main.scss')
.pipe(sass())
.pipe(gulp.dest('css'))
.pipe(browserSync.reload({
stream: true
}))
});
// Minify compiled CSS
gulp.task('minify-css', ['sass'], function() {
return gulp.src('css/main.css')
.pipe(cleanCSS({
compatibility: 'ie8'
}))
.pipe(rename({
suffix: '.min'
}))
.pipe(gulp.dest('css'))
.pipe(browserSync.reload({
stream: true
}))
});
// Minify custom JS
gulp.task('minify-js', function() {
return gulp.src('js/scripts.js')
.pipe(uglify())
.pipe(rename({
suffix: '.min'
}))
.pipe(gulp.dest('js'))
.pipe(browserSync.reload({
stream: true
}))
});
// Copy vendor files from /node_modules into /vendor
// NOTE: requires `npm install` before running!
gulp.task('copy', function() {
gulp.src([
'node_modules/bootstrap/dist/**/*',
'!**/npm.js',
'!**/bootstrap-theme.*',
'!**/*.map'
])
.pipe(gulp.dest('vendor/bootstrap'))
gulp.src(['node_modules/jquery/dist/jquery.js',
'node_modules/jquery/dist/jquery.min.js'])
.pipe(gulp.dest('vendor/jquery'))
gulp.src(['node_modules/jquery-easing/*.js'])
.pipe(gulp.dest('vendor/jquery-easing'))
})
// Default task
gulp.task('default', ['sass', 'minify-css', 'minify-js', 'copy']);
// Configure the browserSync task
gulp.task('browserSync', function() {
browserSync.init({
server: {
baseDir: ''
},
})
})
// Dev task with browserSync
gulp.task('dev', ['browserSync', 'sass', 'minify-css', 'minify-js'], function() {
gulp.watch('scss/*.scss', ['sass']);
gulp.watch('css/*.css', ['minify-css']);
gulp.watch('js/*.js', ['minify-js']);
// Reloads the browser whenever HTML or JS files change
gulp.watch('*.html', browserSync.reload);
gulp.watch('js/**/*.js', browserSync.reload);
});
It depends entirely on your hosting solution and what deployment process you prefer to use. Some of your former questions have the Heroku tag so I assume you use Heroku. If not you can use the second strategy.
One method of using Gulp with Heroku is to automatically run Gulp when you push to the Heroku branch. This is done by having a postinstall script in package.json. Like so:
"scripts": {
..
"postinstall": "gulp"
}
When you push to the remote branch, Heroku will run the build process as normal. After the build process is done it will run the postinstall script. That will run the default task in the gulpfile. This will, of course, run on your Heroku dyno, not on localhost.
If you want to change the different sub tasks that are run during postinstall you can make a new task like this:
gulp.task('deployment', ['minify-css', 'minify-js', 'copy']);
and change the postinstall script to this:
"postinstall": "gulp deployment"
The deployment task will now run instead of the default task.
For this to work you need all the gulp packages in dependencies rather than devDependencies. devDependencies are, after all, not installed on Heroku.
The files that Gulp builds should be added to the .gitignore file. The files that Gulp outputs are often sent to a folder called dist which is kept out of the repository completely. You don't need to have them in the repository as they are being built on Heroku instead.
Another method is to build the files manually yourself before deployment. That means you don't have gulp in the postinstall script (or don't have the postinstall script at all) and keep the gulp packages in devDependencies. The files that are being built should also not be in .gitignore.
Before you deploy you build the files with gulp deployment and then commit them. When you push to Heroku the files will be uploaded like normal, instead of being built there.
This strategy is usually used when you have an ordinary web hosting service.

aws lambda nodejs - error when uploading a zip file compressing by GULP

I'm using Gulp to compress a zip file and then upload it to AWS Lambda. The upload zip file is done manually. Only the process of compressing is handled by Gulp.
Here is my gulpfile.js
var gulp = require('gulp');
var zip = require('gulp-zip');
var del = require('del');
var install = require('gulp-install');
var runSequence = require('run-sequence');
var awsLambda = require("node-aws-lambda");
gulp.task('clean', function() {
return del(['./dist', './dist.zip']);
});
gulp.task('js', function() {
return gulp.src('index.js')
.pipe(gulp.dest('dist/'));
});
gulp.task('npm', function() {
return gulp.src('./package.json')
.pipe(gulp.dest('dist/'))
.pipe(install({production: true}));
});
gulp.task('zip', function() {
return gulp.src(['dist/**/*', '!dist/package.json'])
.pipe(zip('dist.zip'))
.pipe(gulp.dest('./'));
});
gulp.task('deploy', function(callback) {
return runSequence(
['clean'],
['js', 'npm'],
['zip'],
callback
);
});
After running the deploy task, a zip folder named dist.zip is created consists of a index.js file and a node_modules folder. The node_modules folder contains only a lodash library.
This is index.js
var _ = require('lodash');
console.log('Loading function');
exports.handler = (event, context, callback) => {
//console.log('Received event:', JSON.stringify(event, null, 2));
var b = _.chunk(['a', 'b', 'c', 'd', 'e'], 3);
console.log(b);
callback(null, event.key1); // Echo back the first key value
//callback('Something went wrong');
};
After using AWS lambda console to upload the dist.zip folder. There is an error showing that the lodash library cannot be found
{
"errorMessage": "Cannot find module 'lodash'",
"errorType": "Error",
"stackTrace": [
"Function.Module._load (module.js:276:25)",
"Module.require (module.js:353:17)",
"require (internal/module.js:12:17)",
"Object.<anonymous> (/var/task/index.js:1:71)",
"Module._compile (module.js:409:26)",
"Object.Module._extensions..js (module.js:416:10)",
"Module.load (module.js:343:32)",
"Function.Module._load (module.js:300:12)",
"Module.require (module.js:353:17)"
]
}
But in the zip folder, there is a node_modules directory that contains the lodash lib.
dist.zip
|---node_modules
|--- lodash
|---index.js
When i zip the node_modules directory and the file index.js manually, it works fine.
Does anyone have idea what wrongs ? Maybe when compressing using Gulp, there is a misconfigured for the lib path ?
I had same problem few days back.
Everyone pointed to gulp zip, however it was not problem with gulp zip.
Below worked fine:
gulp
.src(['sourceDir/**'], {nodir: true, dot: true} )
.pipe(zip('target.zip'))
.pipe(gulp.dest('build/'));
That is, note the below, in 2nd param of src, in the above:
{nodir: true, dot: true}
That is, we have to include dot files for the zip (ex: .config, .abc, etc.)
So, include above in .src of gulp, else all others like copy, zip, etc. will be improper.
The package gulp-zip is massively popular (4.3k downloads per day) and there does not seem to be any Gulp substitute. The problem is definitely with relative paths and how gulp-zip processes them. Even when using a base path option in the gulp.src function (example below), gulp-zip finds a way to mess it up.
gulp.task("default", ["build-pre-zip"], function () {
return gulp.src([
"dist/**/*"
], { base: "dist/" })
.pipe(debug())
.pipe(zip("dist.zip"))
.pipe(gulp.dest("./dist/"));
});
Since there is no good Gulp solution as of 1/4/2017 I suggest a work-around. I use Gulp to populate the dist folder first, exactly how I need it with the proper node_modules folder. Then it is time to zip the dist folder properly with relative file paths stored. To do that and also update Lambda, I use a batch file (Windows) of command line options to get the job done. Here is the upload.bat file I created to take the place of the gulp-zip task:
start /wait cmd /c "gulp default"
start /wait cmd /c "C:\Program Files\WinRAR\WinRAR.exe" a -r -ep1 dist\dist.zip dist\*.*
aws lambda update-function-code --zip-file fileb://dist/dist.zip --function-name your-fn-name-here
If you use WinRAR you will find their command line docs here, for WinZip go here. That .bat file assumes you are using the AWS Command Line Interface (CLI) which is a godsend; get it here.
If you are wishing this answer pointed you towards a 100% Gulp solution, to that I say, "You and me both!". Good luck.

Gulp not watching correctly

I'm new to using gulp and I think I have it setup correctly, but it does not seem to be doing what it should be doing.
My gulpfile.js has
gulp.task('compass', function() {
return gulp.src('sites/default/themes/lsl_theme/sass/**/*.scss')
.pipe(compass({
config_file: 'sites/default/themes/lsl_theme/config.rb',
css: 'css',
sass: 'scss'
}))
.pipe(gulp.dest('./sites/default/themes/lsl_theme/css'))
.pipe(notify({
message: 'Compass task complete.'
}))
.pipe(livereload());
});
with
gulp.task('scripts', function() {
return gulp.src([
'sites/default/themes/lsl_theme/js/**/*.js'
])
.pipe(plumber())
.pipe(concat('lsl.js'))
.pipe(gulp.dest('sites/default/themes/lsl_theme/js'))
// .pipe(stripDebug())
.pipe(uglify('lsl.js'))
.pipe(rename('lsl.min.js'))
.pipe(gulp.dest('sites/default/themes/lsl_theme/js'))
.pipe(sourcemaps.write())
.pipe(notify({
message: 'Scripts task complete.'
}))
.pipe(filesize())
.pipe(livereload());
});
and the watch function
gulp.task('watch', function() {
livereload.listen();
gulp.watch('./sites/default/themes/lsl_theme/js/**/*.js', ['scripts']);
gulp.watch('./sites/default/themes/lsl_theme/sass/**/*.scss', ['compass']);
});
when I run gulp, the result is
[16:14:36] Starting 'compass'...
[16:14:36] Starting 'scripts'...
[16:14:36] Starting 'watch'...
[16:14:37] Finished 'watch' after 89 ms
and no changes are registered.
for file structure, my gulpfile.js is in the root directory and the sass, css, and js are all in root/sites/default/themes/lsl_theme with the sass folder containing the folder 'components' full of partials.
My assumption is that you are on windows? Correct me if I'm wrong.
There is this problem that gulp-notify tends to break the gulp.watch functions. Try commenting out
// .pipe(notify({
// message: 'Scripts task complete.'
// }))
and see if the problem still exists.
If that does fix the issue, a solution from this thread may be helpful.
You can use the gulp-if
plugin in combination with
the os node module
to determine if you are on Windows, then exclude gulp-notify, like
so:
var _if = require('gulp-if');
//...
// From https://stackoverflow.com/questions/8683895/variable-to-detect-operating-system-in-node-scripts
var isWindows = /^win/.test(require('os').platform());
//...
// use like so:
.pipe(_if(!isWindows, notify('Coffeescript compile successful')))
It turns out that a large part of my issue was just simply being a rookie with Gulp. When I removed 'scripts' from my gulp watch it started working.
I then made the connection that it was watching the same directory that it was placing the new concatenated and minified js files in so it was putting the new file, checking that file, and looping over and over causing memory issues as well as not allowing 'compass' to run.
After creating a 'dest' folder to hold the new js everything started working just peachy.

how to gulp rsync locally

I'm working on site files outside of my local htdocs that I want to deploy to the local site. I will use gulp-watch to watch for changes, but I'm stumbling on just the rsync set up. File structure:
sitename/ --
--htdocs/sites/all/themes/themename
--source/themes/themename
And here's the gulpfile:
var gulp = require('gulp');
var rsync = require('gulp-rsync');
gulp.task('deploy', function() {
gulp.src('source/**')
.pipe(rsync({
root: 'source',
destination: '/htdocs/sites/all'
}));
});
And when I run gulp deploy
[11:36:53] Using gulpfile ~/Sites/sitename/gulpfile.js
[11:36:53] Starting 'deploy'...
[11:36:53] Finished 'deploy' after 5.23 ms
Nothing is written anywhere. Am I missing something obvious...
rsync is short for "remote sync", and thus needs a destination somehwere else than your local system. If you want to synchronize stuff from one directory to the other, just use the built-in gulp methods.
gulp.task('deploy', function() {
gulp.src('source/**')
.pipe(gulp.dest('/htdocs/sites/all');
});
This will copy everything you need to the other folder. If you are looking to also delete files, add this to your watcher:
var watcher = gulp.watch('./source/**/*', ['deploy']);
watcher.on('change', function(ev) {
if(ev.type === 'deleted') {
// path.relative gives us a string where we can easily switch
// directories
del(path.relative('./', ev.path).replace('./source','/htdocs/sites/all'));
}
});

Gulp Watch and Nodemon conflict

Short of it: started using Gulp recently (convert from Grunt), and am trying to use both Gulp's default watch task (not gulp-watch from npm) for SASS/JS/HTML and gulp-nodemon (from npm) to restart an Express server upon changes. When running just gulp watch, it works fine; and when running gulp server (for nodemon) that works fine. However, using both together (shown below in the configuration of the default task), the watch stuff isn't working. The task is running, and on the CLI gulp shows 'Starting' and 'Finished' for the watch tasks, but the files don't update.
Relevant task configurations:
Concat javascript:
gulp.task('js:app', function(){
return gulp.src([
pathSource('js/application/modules/**/*.js'),
pathSource('js/application/_main.js')
])
.pipe(concat('application.js'))
.pipe(gulp.dest('./build/assets/js')).on('error', utils.log);
});
Nodemon, restart on changes to express app:
gulp.task('express', function(){
return nodemon({script:'server.js', ext:'js', cwd: __dirname + '/express', legacyWatch: true})
.on('restart', function(){
//gulp.run('watch'); // doesn't work :(
});
});
Watch javascript changes, and run js:app for concat'ing.
gulp.task('watch', function(){
gulp.watch(pathSource('js/application/**/*.js'), ['js:app']);
});
Default task, to initialize gulp watch and nodemon simultaneously:
gulp.task('default', ['watch', 'express']);
If anyone has any ideas, thanks in advance!
gulp.run calls have been deprecated, so I'd try a different approach. Since you're already using gulp, may I suggest giving gulp-nodemon a try?
As per gulp-nodemon documentation, you can pass it an array of tasks to execute:
UPDATE: Here's the full gulpfile.js file, together with a working sample on github.
'use strict';
// Main dependencies and plugins
var gulp = require('gulp');
var jshint = require('gulp-jshint');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var nodemon = require('gulp-nodemon');
var assets = 'assets/js/**/*.js';
var publicDir = 'public/javascripts';
// Lint Task
gulp.task('lint', function () {
return gulp.src(assets)
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'));
});
// Concatenate and minify all JS files
gulp.task('scripts', function () {
return gulp.src(assets)
.pipe(concat('global.js'))
.pipe(gulp.dest(publicDir))
.pipe(rename('global.min.js'))
.pipe(uglify())
.pipe(gulp.dest(publicDir));
});
// Watch Files For Changes
gulp.task('watch', function () {
gulp.watch(assets, ['lint', 'scripts']);
});
gulp.task('demon', function () {
nodemon({
script: 'server.js',
ext: 'js',
env: {
'NODE_ENV': 'development'
}
})
.on('start', ['watch'])
.on('change', ['watch'])
.on('restart', function () {
console.log('restarted!');
});
});
// Default Task
gulp.task('default', ['demon']);
This way, you spawn the watch task upon nodemon's start and ensure that the watch task is again triggered whenever nodemon restarts your app.
EDIT: seems you should be calling the on-change event from gulp-nodemon, which will handle compile tasks before the restart event triggers.
EDIT: It seems nodemon's on('change', callback) is removed from their API
FWIW, it seems that using the cwd parameter on gulp-nodemon's configuration actually sets the entire gulp cwd to that directory. This means future tasks will be executed in the wrong directory.
I had this problem when running gulp watch tasks on my frontend server at the same time as nodemon tasks on my backend server (in the same gulpfile), there was a race condition wherein if the nodemon command was executed first, the frontend stuff would actually build into (Home)/backend/frontend instead of (Home)/frontend, and everything would go pearshaped from there.
I found that using watch and script params on gulp-nodemon worked around this (although it still looks like nodemon is watching my entire project for changes rather than the built backend directory).