Gulp browser sync breaks scss sourcemaps after injection - gulp

First render sourcemaps refer to scss properly, after injection refers to minificated css.
After reloading browser (manually) sourcemaps works properly again.
package.json (last versions of plugins for today)
...
"devDependencies": {
"gulp": "^4.0.2",
"browser-sync": "^2.26.7",
"gulp-sass": "^4.1.0",
"gulp-sourcemaps": "2.6.5",
"gulp-rename": "^2.0.0",
"vinyl": "^2.2.0", // used for extraStyleDest path
}
gulpfile.js
function extStyle () {
return (
gulp.src( extraStyleSRC )
.pipe(sourcemaps.init())
.pipe(sass())
.on("error", sass.logError)
.pipe(rename({suffix: '.min'}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(extraStyleDest.path))
.pipe(browserSync.stream())
)
}
const watch2 = () => gulp.watch(
extraStyleSRC, gulp.series( extStyle )
);
const bs = () => {
browserSync.init({
proxy: projectURL,
open: true,
injectChanges: true,
port: 8880,
});
};
const dev = gulp.parallel( bs, watch2 );
gulp.task( 'dev', dev );
Results:
chrome dev tools
After injection
after
Any suggestions to fix without reloading?

Related

Gulp + Browsersync is compiling but localhost is not working

I have a Gulp + Browsersync setup which is compiling everything but when I try to view the site in the browser the localhost (Access URLs) is not working.
my code looks like below:
const browsersync = done => {
browserSync.init({
proxy: config.projectURL, // Proxing website.local:8000
open: config.browserAutoOpen, //false
injectChanges: config.injectChanges, //true
watchEvents: [ 'change', 'add', 'unlink', 'addDir', 'unlinkDir' ]
});
done();
};
// Helper function to allow browser reload with Gulp 4.
const reload = done => {
browserSync.reload();
done();
};
Running as follows:
gulp.task(
'default',
gulp.parallel( 'styles', 'customJS', 'images', browsersync, () => {
gulp.watch( config.watchPhp, reload ); // Reload on PHP file changes.
gulp.watch( config.watchStyles, gulp.parallel( 'styles' ) ); // Reload on SCSS file changes.
gulp.watch( config.watchJsCustom, gulp.series( 'customJS', reload ) ); // Reload on customJS file changes.
gulp.watch( config.imgSRC, gulp.series( 'images', reload ) ); // Reload on customJS file changes.
})
);
Any ideas would be greatly appreciated.
Thanks

Gulp + browser-sync doesn't work: 'Cannot GET /'

I am learning the front-end build system currently gulp, i want to use brower-sync and the problem is when it brings up the browser it will not display my html file and it will say "Cannot GET /" error in the browser window. This is my index.js code. Help me 🙏
Thanks :)
import gulp from 'gulp';
import rename from 'gulp-rename';
import sass from 'gulp-sass';
import twig from 'gulp-twig';
import browserSync from 'browser-sync';
gulp.task('style', () => {
console.log('execute sass file');
return gulp.src('src/assets/scss/styles.scss')
.pipe(rename('css/styles.css'))
.pipe(gulp.dest('dist'));
});
gulp.task('index', () => {
console.log('execute twig');
return gulp.src('src/markup/index.twig')
.pipe(rename('html/index.html'))
.pipe(gulp.dest('dist/html'))
});
gulp.task('twig', function() {
return gulp.src('src/markup/*.twig')
.pipe(twig())
.pipe(gulp.dest('dist/html'))
.pipe(browserSync.reload({
stream: true
}))
});
gulp.task('sass', function () {
return gulp.src('src/assets/scss/*.scss')
.pipe(sass())
.pipe(gulp.dest('dist/css'))
.pipe(browserSync.reload({
stream: true
}))
});
gulp.task('watch', function(done) {
gulp.watch('src/assets/scss/**/*.scss', gulp.task('default'));
gulp.watch('src/markup/index.twig', gulp.task('twig'));
console.log('task twig and sass works');
done();
});
gulp.task('browser-sync', () => {
browserSync.init({
server: {
baseDir: 'dist/',
browser:"google chrome",
open: true,
}
});
});
gulp.task('start', gulp.parallel('browser-sync','twig', 'sass', 'watch'));

Gulp-rev will not merge manifest files with correct paths

I can't seem to get gulp-rev to have the correct paths. I've tried everything I can think of.
I have two tasks (among others) one for scripts and one for styles. I can get a merged manifest.json file successfully. However, the paths are not coming through.
Here's the merged manifest.json:
{
...
"main.css": "main-b7877c7599.css",
"main.css.map": "main-b58100898e.css.map",
"main.min.js": "main-00da8f7f74.min.js",
"main.min.js.map": "main-206550c510.min.js.map",
...
}
Here is my gulpfile.babel.js file:
import gulp from 'gulp';
import del from 'del';
import runSequence from 'run-sequence';
import browserSync from 'browser-sync';
import gulpLoadPlugins from 'gulp-load-plugins';
import { output as pagespeed } from 'psi';
import browserify from 'browserify';
import babelify from 'babelify';
import buffer from 'vinyl-buffer';
import source from 'vinyl-source-stream';
const $ = gulpLoadPlugins();
const reload = browserSync.reload;
// Lint JavaScript
gulp.task('lint', () =>
gulp.src(['app/scripts/**/*.js', '!node_modules/**'])
.pipe($.eslint())
.pipe($.eslint.format())
.pipe($.if(!browserSync.active, $.eslint.failAfterError())),
);
// Optimize images
gulp.task('images', () =>
gulp.src('app/images/**/*')
.pipe($.cache($.imagemin({
progressive: true,
interlaced: true,
})))
.pipe(gulp.dest('build/images'))
.pipe($.size({ title: 'images' })),
);
// copy fonts
gulp.task('fonts', () =>
gulp.src('app/fonts/**/*')
.pipe(gulp.dest('build/fonts'))
.pipe($.size({ title: 'fonts' })),
);
// Copy all files at the root level (app)
gulp.task('copy', () =>
gulp.src([
'app/*',
'!app/*.html',
'!app/imports/',
// 'node_modules/apache-server-configs/build/.htaccess',
], {
dot: true,
}).pipe(gulp.dest('build'))
.pipe($.size({ title: 'copy' })),
);
// Compile and automatically prefix stylesheets
gulp.task('styles', () => {
const AUTOPREFIXER_BROWSERS = [
'ie >= 10',
'ie_mob >= 10',
'ff >= 30',
'chrome >= 34',
'safari >= 7',
'opera >= 23',
'ios >= 7',
'android >= 4.4',
'bb >= 10',
];
// For best performance, don't add Sass partials to `gulp.src`
return gulp.src([
'app/styles/**/*.scss',
'app/styles/**/*.css',
])
.pipe($.newer('.tmp/styles'))
.pipe($.sourcemaps.init())
.pipe($.sass({
precision: 10,
includePaths: ['node_modules/susy/sass'],
}).on('error', $.sass.logError))
.pipe($.autoprefixer(AUTOPREFIXER_BROWSERS))
.pipe(gulp.dest('.tmp/styles'))
// Concatenate and minify styles
.pipe($.if('*.css', $.cssnano()))
.pipe($.size({ title: 'styles' }))
.pipe($.sourcemaps.write('./'))
.pipe($.rev())
.pipe(gulp.dest('build/styles'))
.pipe($.rev.manifest('manifest.json', {
cwd: './build',
merge: true,
}))
.pipe(gulp.dest('build/styles'))
.pipe(gulp.dest('.tmp/styles'));
});
gulp.task('scripts', () => {
const b = browserify({
entries: 'app/scripts/main.js',
transform: babelify,
debug: true,
});
return b.bundle()
.pipe(source('main.js'))
.pipe(buffer())
.pipe($.sourcemaps.init({ loadMaps: true }))
.pipe($.sourcemaps.write())
.pipe(gulp.dest('.tmp/scripts'))
.pipe($.concat({ path: 'main.min.js', cwd: '' }))
.pipe($.uglify({ preserveComments: 'some' }))
// Output files
.pipe($.size({ title: 'scripts' }))
.pipe($.sourcemaps.write('.'))
.pipe($.rev())
.pipe(gulp.dest('build/scripts'))
.pipe($.rev.manifest('manifest.json', {
cwd: './build',
merge: true,
}))
.pipe(gulp.dest('build/scripts'))
.pipe(gulp.dest('.tmp/scripts'));
});
// Scan your HTML for assets & optimize them
gulp.task('html', () =>
gulp.src(['app/**/*.html', '!app/imports/*.html'])
.pipe($.fileInclude({
prefix: '##',
basepath: '#file',
}))
.pipe($.useref({
searchPath: '{.tmp,app}',
noAssets: true,
}))
.pipe(gulp.dest('.tmp/'))
// Minify any HTML
.pipe($.if('*.html', $.htmlmin({
removeComments: true,
collapseWhitespace: false,
collapseBooleanAttributes: true,
removeAttributeQuotes: true,
removeRedundantAttributes: true,
removeEmptyAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
removeOptionalTags: true,
})))
// Output files
.pipe($.if('*.html', $.size({ title: 'html', showFiles: true })))
.pipe(gulp.dest('build')),
);
// Clean output directory
gulp.task('clean', () => del(['.tmp', 'build/*', '!build/.git'], { dot: true }));
// Watch files for changes & reload
gulp.task('serve', ['scripts', 'styles', 'html'], () => {
browserSync({
notify: false,
// Customize the Browsersync console logging prefix
logPrefix: 'WSK',
// Allow scroll syncing across breakpoints
scrollElementMapping: ['main', '.mdl-layout'],
// Run as an https by uncommenting 'https: true'
// Note: this uses an unsigned certificate which on first access
// will present a certificate warning in the browser.
// https: true,
server: ['.tmp', 'app'],
port: 3000,
});
gulp.watch(['app/**/*.html'], ['html', reload]);
gulp.watch(['app/styles/**/*.{scss,css}'], ['styles', reload]);
gulp.watch(['app/scripts/**/*.js'], ['lint', 'scripts', reload]);
gulp.watch(['app/images/**/*'], ['images', reload]);
gulp.watch(['app/fonts/**/*'], ['fonts', reload]);
});
// Build and serve the output from the distribution build
gulp.task('serve:build', ['default'], () =>
browserSync({
notify: false,
logPrefix: 'WSK',
// Allow scroll syncing across breakpoints
scrollElementMapping: ['main', '.mdl-layout'],
// Run as an https by uncommenting 'https: true'
// Note: this uses an unsigned certificate which on first access
// will present a certificate warning in the browser.
// https: true,
server: 'build',
port: 3001,
}),
);
// Build production files, the default task
gulp.task('default', ['clean'], cb =>
runSequence(
'copy',
'styles',
['lint', 'html', 'scripts', 'images', 'fonts'],
cb,
),
);
I ended up using gulp-rename to get the correct paths:
.pipe($.rename({
dirname: 'scripts',
}))
.pipe($.rev())
...Similar thing for styles but not merging the manifest files for each, opting to leave them in their respective folders.
And then used gulp-rev-collector to actually update the file mappings referenced in the manifest.
// Revision static asset files
gulp.task('rev', () =>
gulp.src(['build/**/rev-manifest.json', 'build/*.html'])
.pipe($.revCollector())
.pipe(gulp.dest('build')),
);

Gulp compile less files and minify them

I'm new in the use of task runners like Gulp or Grunt, I have chosen to use Gulp to automate my tasks because I'm familiar with Javascript language.
I succeeded to compile my .less files to .css, I even wrote a task to minify my .css files.
I would like to run watch task with BrowSync, which automatically compile .less files to .css and .css to .min.css.
Here's my code :
gulp.task('minifyCSS', () => {
return gulp.src([
'web/assets/css/*.css',
'!web/assets/css/*.min.css'
])
.pipe(sourcemaps.init())
.pipe(cleanCSS())
.pipe(sourcemaps.write())
.pipe(rename({ suffix: '.min'}))
.pipe(gulp.dest('web/assets/css'));});
gulp.task('less', () => {
return gulp.src('web/assets/less/*.less')
.pipe(less())
.pipe(gulp.dest('web/assets/css'))
.pipe(browserSync.reload({
stream: true
}));});
gulp.task('watchSync', ['less', 'minifyCSS', 'browserSync'] , () => {
gulp.watch('web/assets/less/*.less', ['less']);
});
gulp.task('browserSync', () => {
browserSync.init({
notify: false,
browser: "chrome",
proxy: "localhost/web/app_dev.php",
open: false
});});
The browserSync task runs well but it never compiles .css to .min.css. But when I run "gulp minifyCSS" it does the job ...
Do I miss a step ? Can anyone help me on this one ? :)
I'm nearly sure this will work:
gulp.task('minifyCSS', ['less'], () => {
return gulp.src([
'web/assets/css/*.css',
'!web/assets/css/*.min.css'
])
.pipe(sourcemaps.init())
.pipe(cleanCSS())
.pipe(sourcemaps.write())
.pipe(rename({ suffix: '.min'}))
.pipe(gulp.dest('web/assets/css'))
.pipe(browserSync.reload({
stream: true
}))
;
});
gulp.task('less', () => {
return gulp.src('web/assets/less/*.less')
.pipe(less())
.pipe(gulp.dest('web/assets/css'))
;
});
gulp.task('watchSync', ['minifyCSS', 'browserSync'] , () => {
gulp.watch('web/assets/less/*.less', ['minifyCSS']);
});
gulp.task('browserSync', () => {
browserSync.init({
notify: false,
browser: "chrome",
proxy: "localhost/web/app_dev.php",
open: false
});
});

'gulp serve' command remove attached javascript file from index.html

I'm using JHipster to generate my Spring Boot + Angular JS application. It uses Bower to packages managing and Gulp to automate repetable tasks. And I need to add Bootstrap js to my index.html. I've done it manually like follow:
<script src="bower_components/bootstrap/dist/js/bootstrap.js"></script>
I faced with following problem. After run gulp serve command it remove attached definision of Bootstrap js from index.html. And I wondering why.
I will attach my bower.json and gulpfile.js:
`{
"version": "0.0.0",
"name": "sykhivska",
"appPath": "src/main/webapp/",
"testPath": "src/test/javascript/spec",
"dependencies": {
"angular": "1.5.8",
"angular-aria": "1.5.8",
"angular-bootstrap": "1.3.3",
"angular-cache-buster": "0.4.3",
"angular-cookies": "1.5.8",
"ngstorage": "0.3.10",
"angular-loading-bar": "0.9.0",
"angular-resource": "1.5.8",
"angular-sanitize": "1.5.8",
"angular-ui-router": "0.3.1",
"bootstrap": "3.3.7",
"bootstrap-ui-datetime-picker": "2.4.3",
"jquery": "3.1.0",
"json3": "3.3.2",
"messageformat": "0.3.1",
"modernizr": "3.3.1",
"ng-file-upload": "12.0.4",
"ngInfiniteScroll": "1.3.0",
"swagger-ui": "2.1.5"
},
"devDependencies": {
"angular-mocks": "1.5.8"
},
"overrides": {
"angular": {
"dependencies": {
"jquery": "3.1.0"
}
},
"angular-cache-buster": {
"dependencies": {
"angular": "1.5.8"
}
},
"bootstrap": {
"main": [
"dist/css/bootstrap.css"
]
}
},
"resolutions": {
"angular": "1.5.8",
"angular-bootstrap": "2.0.0",
"jquery": "3.1.0"
}
}`
// Generated on 2016-12-11 using generator-jhipster 3.12.1
'use strict';
var gulp = require('gulp'),
rev = require('gulp-rev'),
templateCache = require('gulp-angular-templatecache'),
htmlmin = require('gulp-htmlmin'),
imagemin = require('gulp-imagemin'),
ngConstant = require('gulp-ng-constant'),
rename = require('gulp-rename'),
eslint = require('gulp-eslint'),
del = require('del'),
runSequence = require('run-sequence'),
browserSync = require('browser-sync'),
KarmaServer = require('karma').Server,
plumber = require('gulp-plumber'),
changed = require('gulp-changed'),
gulpIf = require('gulp-if');
var handleErrors = require('./gulp/handle-errors'),
serve = require('./gulp/serve'),
util = require('./gulp/utils'),
copy = require('./gulp/copy'),
inject = require('./gulp/inject'),
build = require('./gulp/build');
var config = require('./gulp/config');
gulp.task('clean', function () {
return del([config.dist], { dot: true });
});
gulp.task('copy', ['copy:fonts', 'copy:common']);
gulp.task('copy:fonts', copy.fonts);
gulp.task('copy:common', copy.common);
gulp.task('copy:swagger', copy.swagger);
gulp.task('copy:images', copy.images);
gulp.task('images', function () {
return gulp.src(config.app + 'content/images/**')
.pipe(plumber({errorHandler: handleErrors}))
.pipe(changed(config.dist + 'content/images'))
.pipe(imagemin({optimizationLevel: 5, progressive: true, interlaced: true}))
.pipe(rev())
.pipe(gulp.dest(config.dist + 'content/images'))
.pipe(rev.manifest(config.revManifest, {
base: config.dist,
merge: true
}))
.pipe(gulp.dest(config.dist))
.pipe(browserSync.reload({stream: true}));
});
gulp.task('styles', [], function () {
return gulp.src(config.app + 'content/css')
.pipe(browserSync.reload({stream: true}));
});
gulp.task('inject', function() {
runSequence('inject:dep', 'inject:app');
});
gulp.task('inject:dep', ['inject:test', 'inject:vendor']);
gulp.task('inject:app', inject.app);
gulp.task('inject:vendor', inject.vendor);
gulp.task('inject:test', inject.test);
gulp.task('inject:troubleshoot', inject.troubleshoot);
gulp.task('assets:prod', ['images', 'styles', 'html', 'copy:swagger', 'copy:images'], build);
gulp.task('html', function () {
return gulp.src(config.app + 'app/**/*.html')
.pipe(htmlmin({collapseWhitespace: true}))
.pipe(templateCache({
module: 'sykhivskaApp',
root: 'app/',
moduleSystem: 'IIFE'
}))
.pipe(gulp.dest(config.tmp));
});
gulp.task('ngconstant:dev', function () {
return ngConstant({
name: 'sykhivskaApp',
constants: {
VERSION: util.parseVersion(),
DEBUG_INFO_ENABLED: true
},
template: config.constantTemplate,
stream: true
})
.pipe(rename('app.constants.js'))
.pipe(gulp.dest(config.app + 'app/'));
});
gulp.task('ngconstant:prod', function () {
return ngConstant({
name: 'sykhivskaApp',
constants: {
VERSION: util.parseVersion(),
DEBUG_INFO_ENABLED: false
},
template: config.constantTemplate,
stream: true
})
.pipe(rename('app.constants.js'))
.pipe(gulp.dest(config.app + 'app/'));
});
// check app for eslint errors
gulp.task('eslint', function () {
return gulp.src(['gulpfile.js', config.app + 'app/**/*.js'])
.pipe(plumber({errorHandler: handleErrors}))
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failOnError());
});
// check app for eslint errors anf fix some of them
gulp.task('eslint:fix', function () {
return gulp.src(config.app + 'app/**/*.js')
.pipe(plumber({errorHandler: handleErrors}))
.pipe(eslint({
fix: true
}))
.pipe(eslint.format())
.pipe(gulpIf(util.isLintFixed, gulp.dest(config.app + 'app')));
});
gulp.task('test', ['inject:test', 'ngconstant:dev'], function (done) {
new KarmaServer({
configFile: __dirname + '/' + config.test + 'karma.conf.js',
singleRun: true
}, done).start();
});
gulp.task('watch', function () {
gulp.watch('bower.json', ['install']);
gulp.watch(['gulpfile.js', 'pom.xml'], ['ngconstant:dev']);
gulp.watch(config.app + 'content/css/**/*.css', ['styles']);
gulp.watch(config.app + 'content/images/**', ['images']);
gulp.watch(config.app + 'app/**/*.js', ['inject:app']);
gulp.watch([config.app + '*.html', config.app + 'app/**', config.app + 'i18n/**']).on('change', browserSync.reload);
});
gulp.task('install', function () {
runSequence(['inject:dep', 'ngconstant:dev'], 'inject:app', 'inject:troubleshoot');
});
gulp.task('serve', ['install'], serve);
gulp.task('build', ['clean'], function (cb) {
runSequence(['copy', 'inject:vendor', 'ngconstant:prod'], 'inject:app', 'inject:troubleshoot', 'assets:prod', cb);
});
gulp.task('default', ['serve']);
This is normal because gulp injects bower dependencies into your index.html based on the bower.json file provided by each dependency, As Bootstrap declares bootstrap.js in own bower.json in its main property, it should be injected. In your case it's not because in your project's bower.json the main property is overriden
"overrides": {
"bootstrap": {
"main": [
"dist/css/bootstrap.css"
]
So either you add "dist/js/bootstrap.js" to your override or you remove completely your bootstrap override from your bower.json.