browsersync + gulp not injecting css - only reloading - npm

I have recently moved to using BrowserSync, I followed their gulp guide and tweaked a few things to solve some issues I was having, however now whilst it works, it appears to reload the page every time rather than inject the CSS.
My gulp file:
var gulp = require('gulp');
var browserSync = require('browser-sync').create();
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var sass = require('gulp-sass');
var postcss = require('gulp-postcss');
var cleanCSS = require('gulp-clean-css');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var autoprefixer = require('autoprefixer');
gulp.task('scripts', function() {
return gulp.src([
'js/dev/main/**/*.js',
// We have to set the bootstrap lines separately as some need to go before others
'js/dev/bootstrap/alert.js',
'js/dev/bootstrap/collapse.js',
'js/dev/bootstrap/tooltip.js',
'js/dev/bootstrap/popover.js',
'js/dev/bootstrap/tab.js',
'js/dev/bootstrap/transition.js',
])
.pipe(sourcemaps.init())
.pipe(concat('scripts.js'))
.pipe(sourcemaps.write('../maps'))
.pipe(gulp.dest('./js'));
});
gulp.task('uglify', ['scripts'], function() {
return gulp.src('js/scripts.js')
.pipe(rename({suffix: '.min'}))
.pipe(uglify({
mangle: false
}))
.pipe(gulp.dest('./js'));
});
// create a task that ensures the `uglify` task is complete before
// reloading browsers
gulp.task('js-watch', ['uglify'], function (done) {
browserSync.reload();
done();
});
/* Creates the standard version */
gulp.task('styles', function() {
return gulp.src('scss/**/*.scss')
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(postcss([
autoprefixer({
browsers: [
'last 4 Chrome versions',
'last 4 Firefox versions',
'last 4 Edge versions',
'last 2 Safari versions',
'ie >= 10',
'> 1.49%',
'not ie <= 9'
],
cascade: false
}),
]))
.pipe(sourcemaps.write('../maps'))
.pipe(gulp.dest('./css/'))
.pipe(browserSync.stream(({match: 'css/**/*.css'})));
});
/* Creates the minified version */
gulp.task('css-minify', ['styles'], function() {
return gulp.src('scss/**/*.scss')
.pipe(sourcemaps.init())
.pipe(sass({
outputStyle: 'compact' // Options: nested, expanded, compact, compressed
}).on('error', sass.logError))
.pipe(postcss([
autoprefixer({
browsers: [
'last 4 Chrome versions',
'last 4 Firefox versions',
'last 4 Edge versions',
'last 2 Safari versions',
'ie >= 10',
'> 1.49%',
'not ie <= 9'
],
cascade: false
}),
]))
.pipe(cleanCSS({
advanced: false,
aggressiveMerging: false
}))
.pipe(rename({suffix: '.min'}))
.pipe(sourcemaps.write('../maps'))
.pipe(gulp.dest('./css/'));
});
gulp.task('browser-sync', function() {
browserSync.init({
open: 'external',
proxy: "bmmedia.dev",
host: 'bmmedia.dev',
// port: 5000,
browser: "chrome",
});
});
gulp.task('watch', ['browser-sync', 'js-watch', 'css-minify'], function() {
gulp.watch(['scss/**/*.scss', 'js/dev/**/*.js'], ['js-watch', 'css-minify']);
});
gulp.task('default', ['js-watch', 'css-minify']);
Notice my watch task, this was the most recent change I did as I was having the problem specified here, and I solved it with this answer, however now whilst it works fine, it appears to only reload, rather than inject.
Is there something I can do to fix this?
Edit:
I just realized it was reloading every time because I was running js-watch every time there was a change, even to .scss files, so I changed it to this:
gulp.task('watch', ['browser-sync', 'js-watch', 'css-minify'], function() {
gulp.watch(['scss/**/*.scss'], ['css-minify']);
gulp.watch(['js/dev/**/*.js'], ['js-watch']);
});
However now it doesn't inject OR reload when a .scss file changes.

I believe I have fixed it...
My watch task I changed to:
gulp.task('watch', ['browser-sync'], function() {
gulp.watch(['scss/**/*.scss'], ['css-minify']);
gulp.watch(['js/dev/**/*.js'], ['js-watch']);
});
Then in my styles task I changed this line:
.pipe(browserSync.stream(({match: 'css/**/*.css'})));
to:
.pipe(browserSync.stream());
Not sure why it wasn't finding the CSS changes, all I know is it now seems to work.

You can also try just watching the compiled output files.
Dest/css/styles.css
Dest/js/my.js
Any changes to a sass / js module would reflect in the final css / js output files. Browser reloading will only fire when the css/js compilation has completed, rather than trying to reload as the sass /js bundles compile.
Also, take a look at Gulp-newer. It can be used for checking / triggering tasks if the final output file (dest/css/styles.css) has been changed relative to the files that made it (src/sass/**.scss).
This is also very handy for images (no need to minify them on each build, only if newer) any other checks you need to perform only if something has changed can also be added.

Related

Gulp terminates immediately when running gulp watch

When I run 'gulp watch' in my terminal, I get this response:
[13:59:40] Using gulpfile ~/path/to/gulpfile.js
[13:59:40] Starting 'watch'...
[13:59:40] Finished 'watch' after 45 ms
Here is the relevant code from my gulpfile.js:
gulp.task('sass', function () {
return gulp.src([baseDir + '/sass/style.scss',baseDir + '/sass/events/events.scss'])
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(autoprefixer({
browsers: ['last 10 versions'],
cascade: false
}))
.pipe(sourcemaps.write())
.pipe(gulp.dest(baseDir + '/css'))
.pipe(livereload());
});
// watch
gulp.task('watch', function () {
livereload.listen();
gulp.watch(baseDir + '/sass/**/*.scss', ['sass']);
});
My problem is this: when I make a change in a .scss file, it is not recognised in the terminal.. why is this?
My gulp version is
version 3.9.1
Local version 3.9.1
When this happens I assume my directory is off. No errors? No files, lol. Have you tried replacing baseDir with a hard coded call to the directory and see what happens? example
gulp.watch('app/sass/**/*.scss', ['sass']);
and see what happens?

r.js minified optimized file not running

BEFORE, I was using r.js to optimize and minify my javascript successfully. I had a main.js file that looked something like this:
require.config({
baseUrl: "scripts/lib",
paths: {
jquery: "http://code.jquery.com/jquery-1.11.2.min",
underscore: "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min",
d3: "d3-for-development",
katex: "https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.3.0/katex.min", // or 0.2.0
mathjax: "http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML&delayStartupUntil=configured",
etc...
},
shim: {
underscore: { exports: "_" },
chosen: { deps: ["jquery"] },
mathjax: {
exports: "MathJax",
init: function (){
MathJax.Hub.Config({
tex2jax: {
inlineMath: [['$','$'], ['\\(','\\)']],
processEscapes: true,
},
});
MathJax.Hub.Startup.onload();
return MathJax;
}
},
},
});
require( [
"jquery",
"underscore",
"browser-detect",
"check-types",
"katex",
"mathjax",
etc
], function(
$,
_,
browser,
check,
katex,
mathjax,
etc
){
/////////////////////////// INITIALIZATION ///////////////////////////
loginInit()
show('#login')
etc...
and I could successfully run node build/r.js -o mainConfigFile=www/scripts/main.js baseUrl=www/scripts/lib name=../main out=www/scripts/main-optimized.min.js generateSourceMap=true preserveLicenseComments=false optimize=uglify2 to minify. Everything worked.
NOW, I have a config.js file that looks like this:
require.config({
urlArgs: "bust=" + new Date().getTime(),
baseUrl: "scripts/lib",
paths: {
jquery: ["jquery-min", "http://code.jquery.com/jquery-1.11.2.min"],
underscore: ["underscore-min", "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min"],
d3: "d3-for-development", // if we add patches separately, then we can just use https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min
katex: ["katex-min", "https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.3.0/katex.min"], // or 0.2.0
mathjax: "http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML&delayStartupUntil=configured",
main: "../main",
etc...
},
shim: {
underscore: { exports: "_" },
chosen: { deps: ["jquery"] },
mathjax: {
exports: "MathJax",
init: function init() {
MathJax.Hub.Config({
tex2jax: {
inlineMath: [['$', '$'], ['\\(', '\\)']],
processEscapes: true }
});
MathJax.Hub.Startup.onload();
return MathJax;
}
}
}
});
require(["main"], function (main) {
// pass. by loading main, we run main.js
});
Instead of passing the minify/optimize arguments straight into the command line, I've created a rbuild.js file for that:
({
mainConfigFile: "../www/scripts/config.js",
baseUrl: "../www/scripts/lib",
name: "../config",
out: "../www/scripts/config-optimized.min.js",
generateSourceMap: true,
preserveLicenseComments: false, // this is necessary for generateSourceMap to work
optimize: "uglify2",
// removeCombined: true,
// findNestedDependencies: true,
paths: {
// https://github.com/jrburke/requirejs/issues/791
// http://www.anthb.com/2014/07/04/optimising-requirejs-with-cdn-fallback
jquery: "jquery-min",
underscore: "underscore-min",
d3: "d3-for-development",
katex: "katex-min",
mathjax: "http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML&delayStartupUntil=configured",
marked: "marked",
chosen: "chosen-min",
jsnetworkx: "jsnetworkx-min",
main: "../main",
},
})
and I run it with node build/r.js -o build/rbuild.js in the command line. It appears to run successfully and makes the config-optimized.min.js file, as expected. The output is:
Tracing dependencies for: ../config
Cannot optimize network URL, skipping: http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML&delayStartupUntil=configured
Uglify2 file: /Users/Matthew/programming/prove-math/www/scripts/config-optimized.min.js
/Users/Matthew/programming/prove-math/www/scripts/config-optimized.min.js
----------------
/Users/Matthew/programming/prove-math/www/scripts/lib/jquery-min.js
/Users/Matthew/programming/prove-math/www/scripts/lib/underscore-min.js
/Users/Matthew/programming/prove-math/www/scripts/lib/browser-detect.js
/Users/Matthew/programming/prove-math/www/scripts/lib/check-types.js
/Users/Matthew/programming/prove-math/www/scripts/lib/katex-min.js
/Users/Matthew/programming/prove-math/www/scripts/lib/profile.js
/Users/Matthew/programming/prove-math/www/scripts/lib/marked.js
/Users/Matthew/programming/prove-math/www/scripts/lib/d3-for-development.js
/Users/Matthew/programming/prove-math/www/scripts/lib/user.js
/Users/Matthew/programming/prove-math/www/scripts/lib/graph-animation.js
/Users/Matthew/programming/prove-math/www/scripts/lib/graph.js
/Users/Matthew/programming/prove-math/www/scripts/lib/node.js
/Users/Matthew/programming/prove-math/www/scripts/lib/blinds.js
/Users/Matthew/programming/prove-math/www/scripts/lib/chosen-min.js
/Users/Matthew/programming/prove-math/www/scripts/main.js
/Users/Matthew/programming/prove-math/www/scripts/lib/../config.js
But when I visit index.html via my server, the page is blank. The JS console gives no errors or log messages, which suggests that no JS is being run. My server gives no errors, which suggests that everything has been sent to the client successfully, and the client JS is not running.
So I'm pretty convinced the JS is there but not running. Is there something wrong with my setup that causes config.js to not run the code? With no error messages, I am having trouble troubleshooting :)
So I commented out
generateSourceMap: true,
preserveLicenseComments: false, // this is necessary for generateSourceMap to work
optimize: "uglify2",
and it worked! THEN, I uncommented that stuff, and it STILL worked!
It seems that as of requireJS 2.2 (I was using RequireJS 2.1.6 BEFORE), you can now use
optimize: "uglify",
or nothing at all, since this is the default setting. As of requireJS 2.2, it DOES use uglify2 in this case. This is the closest thing to an explanation that I can give :/

I'm trying to use Karma + Mocha for the first time

I'm trying to use Karma + Mocha for the first time.
The main condition is to run the unit tests in a Docker container without any GUI. I don't have any browser, and my only choice is to use PhantomJS.
I have configured all necessary plugins, configs etc., but I received the following error:
ReferenceError: Can't find variable: exports
Before the test run, I built the JavaScript source code with Babel to the 'build' directory and then started Karma from there.
What could be causing this problem?
Here is my karma.conf.js:
// Karma configuration
// Generated on Mon Apr 25 2016 13:04:28 GMT+0300 (RTZ 2 (зима))
const path = require('path');
const webpack = require('webpack');
module.exports = function(config) {
var confBuilder = require('./webpack.config');
confBuilder.module.loaders.push({
test: /\.jsx$/,
loader: 'isparta',
include: path.resolve('src'),
});
confBuilder.devtool = 'inline-source-map';
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha', 'chai'/*'jasmine' /*, 'requirejs'*/],
// list of files / patterns to load in the browser
files: [
{pattern: 'build/utils/*.js', load: false}
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'tests.webpack.js': ['webpack', 'sourcemap'],
'build/utils/*.js': ['babel']
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['mocha', 'coverage', 'jenkins'],
plugins: [
require('karma-webpack'),
require('karma-mocha'),
require('karma-chai'),
require('karma-mocha-reporter'),
require('karma-jenkins-reporter'),
require('karma-chrome-launcher'),
require('karma-sourcemap-loader'),
require('karma-coverage'),
require('karma-phantomjs-launcher'),
require('karma-requirejs'),
require('karma-babel-preprocessor')
],
webpack: confBuilder,
webpackServer: {
noInfo: true,
},
coverageReporter: {
check: {
global: {
statements: 86,
branches: 80,
functions: 95,
lines: 40,
},
},
},
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true,
autoWatch: true,
})
}

GULP LESS Imports not working in gulp-less npm

Having used Gulp all the time for 2 last years, I've suddenly got a problem with the less file imports and just can not resolve it.
I've tried more then 5 combinations, such as from SmashingMagazine, from gulp-less homepage, etc... none worked for me.
The problem is (error log in console output):
C:\wamp\www\lumenframe>gulp less
[10:23:25] Using gulpfile C:\wamp\www\lumenframe\Gulpfile.js
[10:23:25] Starting 'less'...
Potentially unhandled rejection [2] '/bower_components/animate.css/animate.css' wasn't found. Tried - /bower_components/animate.css/animate.c
ss,bower_components\bootstrap\less\bower_components\animate.css\animate.css,bower_components\animate.css\bower_components\animate.css\animate
.css,bower_components\font-awesome\less\bower_components\animate.css\animate.css in file C:\wamp\www\lumenframe\bower_components\assets\l
ess\appstrap.less line no. 43
Gulpfile.js looks like this:
// Init Gulp
var gulp = require('gulp');
// Dependencies
var less = require('gulp-less'),
concat = require('gulp-concat'),
rename = require('gulp-rename'),
uglify = require('gulp-uglify'),
autoprefixer = require('gulp-uglify');
// Folder paths
var jsdir = './bower_components/assets/js/',
jspub = './public/assets/js/',
lessdir = './bower_components/assets/less/',
lesspub = './public/assets/css/';
// LESS compiler
gulp.task('less', function () {
return gulp.src(lessdir + 'frontend.less')
.pipe(less({
compress: true,
paths: [
'./bower_components/bootstrap/less/',
'./bower_components/animate.css/',
'./bower_components/font-awesome/less/'
]
}))
.pipe(autoprefixer('last 10 versions', 'ie 9'))
.pipe(gulp.dest(lesspub));
});
// Concatenate and Minify JS
gulp.task('scripts', function () {
return gulp.src(jsdir + '*.js')
.pipe(concat('appstrap.js'))
.pipe(gulp.dest(jspub))
.pipe(rename('appstrap.min.js'))
.pipe(uglify())
.pipe(gulp.dest(jspub));
});
// Filewatcher for changes
gulp.task('watch', function () {
gulp.watch(jsdir + '*.js', ['scripts']);
gulp.watch(lessdir + '*.less', ['less']);
});
// Default Task combination
gulp.task('default', ['less', 'scripts', 'watch']);
All files are in their proper place, so they exists. And once I do #import appstrap.less, it comes out with the error **Potentially unhandled rejection [2].
frontend.less looks like this:
// Core source files of the whole frontend plugins
#import (once) "appstrap.less";
.btn{
color: #ff0000;
display: block;
}
Any visible errors ?

Karma, empty test suite

First of all I know there are similar questions, but none of it works for me.
I have an Angular app, and I would like to test it with Karma, Jasmin, and RequireJs.
I have installed everything I need, and configured everything as it is written here: http://karma-runner.github.io/0.13/plus/requirejs.html
Below is how my files look like
karma.conf.js
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine', 'requirejs'],
// list of files / patterns to load in the browser
files: [
'src/test/Tests/*.js',
'src/test/Tests/directives/*.js',
//source code
{pattern: 'src/main/webapp/app/*.js', included: false},
{pattern: 'src/main/webapp/app/**/*.js', included: false},
{pattern: 'src/test/test-main.js', included: true}
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'test/Tests/*.js': 'coverage'
},
coverageReporter:{
type:'html',
dir:'../coverage/'
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress', 'coverage'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['PhantomJS'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultanous
concurrency: Infinity
})
}
test-main.js
var TEST_REGEXP = /(spec|test)\.js$/i;
var allTestFiles = [];
// Get a list of all the test files to include
Object.keys(window.__karma__.files).forEach(function(file) {
if (TEST_REGEXP.test(file)) {
// Normalize paths to RequireJS module names.
// If you require sub-dependencies of test files to be loaded as-is (requiring file extension)
// then do not normalize the paths
var normalizedTestModule = file.replace(/^\/base\/|\.js$/g, '');
allTestFiles.push(normalizedTestModule);
}
});
require.config({
// Karma serves files under /base, which is the basePath from your config file
baseUrl: '/base',
//dynamically load all test files
deps: allTestFiles,
// we have to kickoff jasmine, as it is asynchronous
callback: window.__karma__.start
});
The output is in IntelliJ IDEA 14.1.5
Empty test suite.
Process finished with exit code 0
The server starts correctly. I have also tried with command line. $ karma start, and $ karma run, which also does nothing. There is no error message at all. The path is correct, there is no 404 error.
Do you have any guess what could be the problem?
Delete the module names from test files.
In my case, this was the solution.
According to RequireJS documentation (http://requirejs.org/docs/api.html#modulename) you can include a name for the module as you can see below:
//Explicitly defines the "foo/title" module:
define("foo/title",
["my/cart", "my/inventory"],
function(cart, inventory) {
//Define foo/title object in here.
}
);
But for me, Karma only executes the tests if I delete the "foo/title" name.