Gulp 4 Sass + BrowserSync Injection with MAMP - javascript

I've spent the whole day trying to figure this out right. I am aware of
Gulp 4 & BrowserSync: Style Injection?
and tried different approaches to this. What am I missing?
I am trying to get gulp to inject the sass generated style to the browser. As of now, it does open a new tab with the generated css, but it does neither refresh nor inject the newly generated style when changing. I get:
[Browsersync] Watching files...
[21:27:36] Starting 'buildStyles'...
[21:27:36] Finished 'buildStyles' after 40 ms
[Browsersync] File event [change] : site/templates/styles/main.css
But it doesn't inject. Here's my gulpfile.js:
const { src, dest, watch, series, parallel } = require('gulp');
const sass = require('gulp-sass');
const browsersync = require('browser-sync').create();
const paths = {
sass: {
// By using styles/**/*.sass we're telling gulp to check all folders for any sass file
src: "site/templates/styles/scss/*.scss",
// Compiled files will end up in whichever folder it's found in (partials are not compiled)
dest: "site/templates/styles"
},
css: {
src: "site/templates/styles/main.css"
}
};
function buildStyles(){
return src(paths.sass.src)
.pipe(sass())
.on("error", sass.logError)
.pipe(dest(paths.sass.dest))
}
function watchFiles(){
watch(paths.sass.src,{ events: 'all', ignoreInitial: false }, series(buildStyles));
}
function browserSync(done){
browsersync.init({
injectChanges: true,
proxy: "http://client2019.local/",
port: 8000,
host: 'client2019.local',
socket: {
domain: 'localhost:80'
},
files: [
paths.css.src
]
});
done();
// gulp.watch("./**/*.php").on("change", browserSync.reload);
}
exports.default = parallel(browserSync, watchFiles); // $ gulp
exports.sass = buildStyles;
exports.watch = watchFiles;
exports.build = series(buildStyles); // $ gulp build
What am I missing?

I don't know if I fully understand what are you want.
To auto refresh the browser with BrowserSync, after saving your last changes, I'm using this code on my gulp file:
var paths = {
styles: {
src: "./src/styles/scss/**/*.scss",
dest: "./view/styles"
},
htmls: {
src: "./src/**/*.html",
dest: "./view"
}
};
const styles= () => {
return...
}
const html= () => {
return...
}
const watch = () => {
browserSync.init({
server: {
baseDir: "./view"
}
});
gulp.watch(paths.styles.src, style);
gulp.watch(paths.htmls.src, html);
gulp.watch("src/**/*.html").on('change', browserSync.reload);
};
exports.style = style;
exports.html = html;
exports.watch = watch;
var build = gulp.parallel(style, html, watch);
gulp.task('default', working);
Then I just execute gulp for build and watch with auto reload.

Related

Gulp 4 - watch not watching changes

Today I migrated to Gulp 4, but I'm not able to get my watch function to work.
// Watch
gulp.task('watch', gulp.series('typescript', 'sass', 'browserSync', function(){
gulp.watch('./app/styles/**/*.scss', gulp.series('sass'));
gulp.watch('app/scripts/**/*.ts', gulp.series('typescript'));
gulp.watch('./app/*.html', browserSync.reload);
}));
typescript, sass, browserSync will run but watch does not react to file changes.
I just had the same problem. You don't actually have a reference to the initialized browserSync inside your watch gulp task. Instead of having your browserSync.init function in a separate browserSync gulp task, move it to inside your watch task, and it should work. Hope this helps!
Example:
gulp.task('watch', gulp.series(function (){
browserSync.init({
proxy:"http://localhost:8888",
injectChanges: true,
plugins: ["bs-html-injector?files[]=*.html"]
});
var html = gulp.watch('development/index.html');
html.on('change', function(path, stats) {
console.log('you changed the html');
browserSync.notify("Compiling, please wait!");
browserSync.reload("index.html");
})
var js = gulp.watch('development/**/*.js');
js.on('change', function(path, stats) {
console.log('you changed the js');
browserSync.notify("Compiling, please wait!");
browserSync.reload();
})
var css = gulp.watch('development/**/*.css');
css.on('change', function(path, stats) {
console.log('you changed the css');
browserSync.notify("Injecting CSS!");
browserSync.reload("*.css");
})
}));
Change gulp.watch('app/scripts/**/*.ts', gulp.series('typescript')); to a absolute gulp.watch('./app/scripts/**/*.ts', gulp.series('typescript'));
Also i normally stick this syntax, per task.
var watcher = gulp.watch('js/**/*.js', gulp.parallel('concat', 'uglify'));
watcher.on('change', function(path, stats) {
console.log('File ' + path + ' was changed');
});
I had some issues too, and i found this tutorial of gulp 4, this is my gulpfile to compile scss and watch the Scss files, concat and compile to a main.min.css with autoprefix.
var gulp = require('gulp'),
concat = require('gulp-concat'),
autoprefixer = require('gulp-autoprefixer'),
sass = require('gulp-sass');
//task para o sass
var paths = {
styles: {
src: 'scss/**/*.scss',
dest: 'css'
}
};
function styles() {
return gulp
.src(paths.styles.src, {
sourcemaps: true
})
.pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
.pipe(concat('main.min.css'))
.pipe(autoprefixer({
browser: ['last 2 version', '> 5%'],
cascade: false
}))
.pipe(gulp.dest(paths.styles.dest));
}
function watch() {
gulp.watch(paths.styles.src, styles);
}
var build = gulp.parallel(styles, watch);
gulp.task(build);
gulp.task('default', build);
I think that on the gulp v4 you need to use the gulp.parallel. I'm digging to learn more about the new version.

Gulp not creating CSS file in destination

I am trying to set the Gulp tasks for styles with postcss, CSS modules etc., but for now only the watch task for the main HTML file is working, and it is not even creating the main CSS file nor the temp folder so I get the error in the console that it can not find the styles.css. It's driving me crazy for days but just cannot get to the bottom of it. Here is my file structure, pretty basic:
application -> views -> index.html
public -> gulp -> tasks -> styles.js, watch.js
-> styles (styles.css inside, base and modules for CSS subfolders)
And here are the styles and watch tasks:
var gulp = require('gulp'),
watch = require('gulp-watch'),
browserSync = require('browser-sync').create();
gulp.task('watch', function() {
browserSync.init({
notify: false,
server: {
baseDir: "../application/views"
}
});
watch('../application/views/index.html', function(){
browserSync.reload();
});
watch('../application/public/styles/**/*.css', function(){
gulp.start('cssInject');
});
});
gulp.task('cssInject', ['styles'], function(){
return gulp.src('../application/temp/styles')
.pipe(browserSync.stream());
});
Styles:
var gulp = require('gulp'),
postcss = require('gulp-postcss'),
autoprefixer = require('autoprefixer'),
cssvars = require('postcss-simple-vars'),
nested = require('postcss-nested'),
cssImport = require('postcss-import'),
mixins = require('postcss-mixins'),
hexrgba = require('postcss-hexrgba');
gulp.task('styles', function(){
return gulp.src('../application/public/styles/styles.css')
.pipe(postcss([cssImport, mixins, cssvars, nested, hexrgba, autoprefixer]))
.on('error', function(errorInfo){
console.log(errorInfo.toString());
this.emit('end');
})
.pipe(gulp.dest('../application/temp/styles'));
});
If someone can give a piece of advice I would be really grateful.

Css stylesheet has the wrong path when using gulp

I have been struggling for a while now and it is fairly frustrating to be honest.
The problem:
I created a gulpfile for my static website, and all i want to do is use browserSync, to compile sass into css and to minify the script and css files. Everything works fine, excluding one thing:
When I run "gulp" everything loads, besides de css file, which is located in "CSS/". Apparently the server thinks that the css file is ("CSS/style.css/") a folder actually.
Screenshot with the console error:
image
the css file is located in "css/style.css"
"use strict";
let paths = {
script: "js/*.js",
minifiedScript: 'script.min.js',
cssPath: "css/*.css",
productionFolder: "production",
sassPath: "scss/*.scss",
htmlFiles: "*.html"
};
const gulp = require('gulp');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
const sourcemaps = require('gulp-sourcemaps');
const del = require('del');
const browserSync = require('browser-sync').create();
const cssMin = require('gulp-css');
const sass = require('gulp-sass');
const inject = require('gulp-inject');
const rename = require("gulp-rename");
gulp.task('browserSync', function() {
browserSync.init({
server: {
baseDir: "./"
}
});
});
gulp.task('sass', function () {
return gulp.src(paths.sassPath)
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./css'))
.pipe(browserSync.stream());
});
gulp.task('index', function () {
var target = gulp.src('index.html');
// It's not necessary to read the files (will speed up things), we're only after their paths:
var sources = gulp.src([paths.script,paths.cssPath], {read: false});
return target.pipe(inject(sources))
.pipe(gulp.dest(''));
});
gulp.task('cssMinify', function(){
return gulp.src(paths.cssPath)
.pipe(cssMin())
.pipe(gulp.dest(paths.productionFolder + "/minified css"))
.pipe(browserSync.stream());
});
gulp.task('clean', function() {
// You can use multiple globbing patterns as you would with `gulp.src`
return del(['build']);
});
gulp.task('scripts', ['clean'], function() {
// Minify and copy the JS file
return gulp.src(paths.script)
.pipe(sourcemaps.init())
.pipe(uglify())
.pipe(concat(paths.minifiedScript))
.pipe(sourcemaps.write())
.pipe(gulp.dest(paths.productionFolder + "/minified JS"));
});
gulp.task('jsMinify:watch', function() { gulp.watch(paths.script, ['scripts']) });
gulp.task('sass:watch', function() { gulp.watch(paths.sassPath, ['sass']) });
gulp.task('cssMinify:watch', function() { gulp.watch(paths.cssPath, ['cssMinify']) });
gulp.task('html:watch', function() { gulp.watch(paths.htmlFiles).on('change', browserSync.reload) });
gulp.task('default', ['sass', 'index', 'cssMinify', 'clean', 'html:watch', 'jsMinify:watch', 'sass:watch', 'cssMinify:watch','browserSync', 'scripts']); // DEVELOPMENT

When I run gulp, unexpected error pops up(event.js : 160)

Here is the snapshot of command prompt when I run gulp. Previously it used to work correctly but now, it is showing some weird errors.
my view folder is supposed to contain only templates, so why is it displaying bootstrap.social.css not found?
and my project folder looks like-
Project-
app-
fonts-...
images-...
scripts-
app.js
controllers.js
services.js
styles-...
index.html
views-
various html templates
bower_components-...
dist-..
node_modules-...
gulpfile.js
package.json
...
here is my gulpfile.js' code:
var gulp = require('gulp'),
minifycss = require('gulp-minify-css'),
jshint = require('gulp-jshint'),
stylish = require('jshint-stylish'),
uglify = require('gulp-uglify'),
usemin = require('gulp-usemin'),
imagemin = require('gulp-imagemin'),
rename = require('gulp-rename'),
concat = require('gulp-concat'),
notify = require('gulp-notify'),
cache = require('gulp-cache'),
changed = require('gulp-changed'),
rev = require('gulp-rev'),
browserSync = require('browser-sync'),
ngannotate = require('gulp-ng-annotate'),
del = require('del');
gulp.task('jshint', function() {
return gulp.src('app/scripts/**/*.js')
.pipe(jshint())
.pipe(jshint.reporter(stylish));
});
// Clean
gulp.task('clean', function() {
return del(['dist']);
});
// Default task
gulp.task('default', ['clean'], function() {
gulp.start('usemin', 'imagemin','copyfonts');
});
gulp.task('usemin',['jshint'], function () {
return gulp.src('./app/**/*.html')
.pipe(usemin({
css:[minifycss(),rev()],
js: [ngannotate(),uglify(),rev()]
}))
.pipe(gulp.dest('dist/'));
});
// Images
gulp.task('imagemin', function() {
return del(['dist/images']), gulp.src('app/images/**/*')
.pipe(cache(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })))
.pipe(gulp.dest('dist/images'))
.pipe(notify({ message: 'Images task complete' }));
});
gulp.task('copyfonts', ['clean'], function() {
gulp.src('./bower_components/font-awesome/fonts/**/*.{ttf,woff,eof,svg}*')
.pipe(gulp.dest('./dist/fonts'));
gulp.src('./bower_components/bootstrap/dist/fonts/**/*.{ttf,woff,eof,svg}*')
.pipe(gulp.dest('./dist/fonts'));
});
// Watch
gulp.task('watch', ['browser-sync'], function() {
// Watch .js files
gulp.watch('{app/scripts/**/*.js,app/styles/**/*.css,app/**/*.html}', ['usemin']);
// Watch image files
gulp.watch('app/images/**/*', ['imagemin']);
});
gulp.task('browser-sync', ['default'], function () {
var files = [
'app/**/*.html',
'app/styles/**/*.css',
'app/images/**/*.png',
'app/scripts/**/*.js',
'dist/**/*'
];
browserSync.init(files, {
server: {
baseDir: "dist",
index: "index.html"
}
});
// Watch any files in dist/, reload on change
gulp.watch(['dist/**']).on('change', browserSync.reload);
});

gulpfile.js is not concatenating all css after sass build

This is my gulpfile.js
"use strict";
var gulp = require('gulp');
var connect = require('gulp-connect'); //Runs a local dev server
var open = require('gulp-open'); //Open a URL in a web browser
var browserify = require('browserify'); // Bundles JS
var reactify = require('reactify'); // Transforms React JSX to JS
var source = require('vinyl-source-stream'); // Use conventional text streams with Gulp
var concat = require('gulp-concat'); //Concatenates files
var lint = require('gulp-eslint'); //Lint JS files, including JSX
var livereload = require('gulp-livereload');
var sass = require('gulp-sass');
var config = {
port: 9005,
devBaseUrl: 'http://localhost',
paths: {
html: './src/*.html',
js: './src/**/*.js',
scss: [
'node_modules/font-awesome/scss/font-awesome.scss',
'./src/scss/default.scss'
],
sassBuilds: './src/builds/css/',
css: [
'node_modules/bootstrap/dist/css/bootstrap.min.css',
'node_modules/bootstrap/dist/css/bootstrap-theme.min.css',
'./src/builds/css/*.css'
],
fonts:[
'node_modules/font-awesome/fonts/**.*'
],
dist: './dist',
mainJs: './src/main.js'
}
}
//Start my local development server
gulp.task('connect', function() {
connect.server({
root: ['dist'],
port: config.port,
base: config.devBaseUrl,
livereload: true
});
});
gulp.task('open', ['connect'], function() {
gulp.src('dist/index.html')
.pipe(open({ uri: config.devBaseUrl + ':' + config.port + '/', app: 'Chrome'}));
});
gulp.task('livereload', function (){
gulp.src('./src/**/*')
.pipe(connect.reload());
});
gulp.task('html', function() {
gulp.src(config.paths.html)
.pipe(gulp.dest(config.paths.dist))
.pipe(connect.reload());
});
gulp.task('js', function() {
browserify(config.paths.mainJs)
.transform(reactify) //this would 'bundle' the JSX
.bundle()
.on('error', console.error.bind(console))
.pipe(source('bundle.js'))
.pipe(gulp.dest(config.paths.dist + '/scripts'))
.pipe(connect.reload());
});
gulp.task('css', function() {
gulp.src(config.paths.css)
.pipe(concat('bundle.css'))
.pipe(gulp.dest(config.paths.dist + '/css'));
});
gulp.task('lint', function() {
return gulp.src(config.paths.js)
.pipe(lint({config: 'eslint.config.json'}))
.pipe(lint.format());
});
gulp.task('watch', function() {
gulp.watch(config.paths.html, ['html', 'livereload']);
gulp.watch(config.paths.scss, ['sass', 'livereload']);
gulp.watch(config.paths.js, ['js', 'lint']);
});
gulp.task('sass', function () {
return gulp.src(config.paths.scss)
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest(config.paths.sassBuilds));
});
gulp.task('icons', function() {
return gulp.src(config.paths.fonts)
.pipe(gulp.dest(config.paths.dist + '/fonts'));
});
gulp.task('default', ['html', 'sass', 'js', 'lint', 'css', 'icons', 'open', 'watch']);
sass task first runs to create 2 css files into builds/css/
After that css task runs and should concat all css files from the config.paths.css but it doesn't, only watch task does and barely, sometimes it does, sometimes it doesn't (seriously). I feel there is some spaghetti going on here.
If you are expecting that the sass task will always finish before the css task starts Don't. From the gulp documentation
Note: The tasks will run in parallel (all at once), so don't assume that the tasks will start/finish in order.
The usual way to fix this is to make the css task wait for the sass task to finish by:
gulp.task('css', ['sass'], function() {

Categories