browsersync only reloads 'root' index.html - gulp

I am working on a website build tool (https://github.com/bmargogne/website-builder.git). BrowserSync works perfectly while being on the root index.html, but it does not reload anywhere else...
Here is the (simplified) way of how I did... Let's say I have :
src/index.html
src/_header.html
src/page/index2.Html
One task builds HTML pages by including html partials (their names start with '_')
gulp.task('pagesHtml', () => {
const SRC = 'src/**/*.html';
const EXCLUDE = '!src/**/_*.html';
return gulp.src( [SRC, EXCLUDE], { ignoreInitial: false } )
pipe( fileinclude({ prefix: '##', basepath: co.src }))
.pipe( gulp.dest( 'www/' ));
});
One task start browser Sync server
gulp.task('serveLocal', () => {
return browserSync.init({
server:{ baseDir : 'www' },
port: 3000,
open: true
});
});
One task is called to reload browserSync (separated, as it is called by other 'watchers tasks' from my project)
gulp.task('liveReload', ()) => {
browserSync.reload();
});
And one task watch all HTML (including partials) and should rebuild the whole page, then reload.
gulp.task('watch-pagesHtml', () => {
const SRC = 'src/**/*.html';
return watch( SRC, () => {
runSequence('pagesHtml', 'liveReload');
});
return;
});
I start these tasks by starting runSequence like this :
gulp.task('default', () => {
runSequence('pagesHtml', 'watch-pagesHtml');
});
When I work on index or _header : No problems at all! The changes are applied, built, and the browse reloads.
However, when I work on pages/index2, the changes are applied and built, but the browser does not reload. (though a F5 works and shows the change applied )
What did I do wrong ?

Browsersync works by injecting an asynchronous script tag in the body, start your project and inspect the body tag. (With browser developer tool).
If you can't fine something like:
<script async>...</script> (and browsersync stuffs), there is the problem.
I read your code, and I notice that you write the <body> (open tag) in header file, and </body> (close tag)in other footer file, and it is confusing but I did not find the body tag in the other html files when I think that was necessary.
The browser "try" to fix errors in the html, auto completing tags from the original html file for example.
I have two possible answers to your problem.
1) The browser autocomplete the tag in the header file, an also autocomplete the tag in the footer file, so browsersync have problems to inject de asynchronous script tag that is necessary to reload the page because there are two bodies. (if this is possible)
2) The browser do not find the body tag in the html, so the browser create it after, but browsersync inject the script in your html file, not in the browser.
Make sure that the body tag is generated by your own code and not by the browser.
I hope that helps.

A bit late but if someone still looking for an answer, you can do something like that:
var browserSync = require("browser-sync");
browserSync({
proxy: "wordpress.dev",
snippetOptions: {
ignorePaths: "wp-admin/**"
}
});

Related

browsersync reload when a nunjucks partial file is modified

I have a gulp task as following:
gulp.task("nunjucks", () => {
return gulp
.src([src_folder + "pages/**/*.njk"])
.pipe(plumber())
.pipe(
data(() =>
JSON.parse(fs.readFileSync(src_folder + "datas/dist/data.json"))
)
)
.pipe(nunjucks())
.pipe(beautify.html({ indent_size: 2 }))
.pipe(gulp.dest(dist_folder))
.pipe(browserSync.stream({match: '**/*.html'}));
});
gulp.watch([src_folder + '**/*.njk'], gulp.series("nunjucks")).on("change", browserSync.reload);
and my project structures look like this:
atoms, molecules and organisms contains nunjucks partials.
The problem I have is that whenever I update a partial file (ex: organisms/partial1.njk), my task detects changes on all the files inside pages (the path I provided for the task src), as you can see here :
I only want to reload the files that includes this partial and not all the files.
How can I solve this?
Its not up to your gulp task to know which one of your Nunjuck pages contain partials. Perhaps if you re-group your .njk files within your Pages folder, you could then better manage what gets reloaded. The following is untested, but hopefully conveys the idea...
pages/
- init/
- other-stuff/
You could then update the src from your gulp task to something like so...
gulp.src([
'!pages/other-stuff/**/*',
'pages/init/**/*.njk'
])

nodejs sendfile html page

I have this code that allows me to open a HTML page from specific folder, if I use server.js to open that HTMLpage so the page it is generating with all the css and jquery files but if I try to move the get statement to the routes folder then the page is generated but without any css and jquery files and I don't know why !
what I did in the server.js for the generation of the HTML page is below which is working perfectly :
const folderPath = __dirname + '/public/AppTemplate/src'
app.use(express.static(folderPath))
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname + '/public/AppTemplate/src/index.html'));
});
but what I'm trying now is to get the html page from routes.js :
step 1 :
I implemented this statement in server.js
app.use('/users', require('./backend/routes/profile.routes.js'));
step2 :I tried this statement in routes.js with simple modification :D :
router.get('/profile', function (req, res) {
const dirname = __dirname;
console.log(dirname)
const newpath = dirname.length - 14;
const newP = dirname.substring(newpath, dirname.lastIndexOf("/"));
console.log(newP);
res.sendFile(path.join(newP+ '/public/AppTemplate/src/02-ProfilePage.html'));
});
the step 2 is working but I couldn't get all the associated files (jquery css ...) which are located in
/public/AppTemplate/src
the image of the output is below :
hope I mentioned everything,
Best Regards,
It's because of the content in the 02-ProfilePage.html has an incorrect path.
Check the path in the script tags. If there is a slash it means that it's already in the /public/AppTemplate/src which you specified.
For example, /js/file.js will actually point to /public/AppTemplate/src/js/file.js
Perhaps try adding a / in front of your path in the script tag.
Example:
/css/x/y/z/ instead of css/x/y/z
You will have to append a / to all the routes in your script/link tag to be able to successfully load the local resources.
You can use the find and replace functionality in your code editor or IDE to speed up the process if possible.

gulp-clean and del does not work to clean the folder i want

I don't understand what i'm doing wrong. I want to clean up my dist/browser folder, but absolutely noothing happens, not even an error.
const gulp = require("gulp");
const gulpElm = require('gulp-elm');
const clean = require('gulp-clean');
const del = require('del');
gulp.task("clean-dist/browser-folder", () => {
console.log("this gets logged - and nothing happens.");
return gulp.src('dist/**', {read: false})
.pipe(clean({force: true}));
});
// i commented this out but this 2 aproaches below using del module also don't work
// gulp.task("clean-dist/browser-folder", () => {
// return del([ "dist/browser"], {force:true});
// });
// gulp.task("clean-dist/browser-folder", async () => {
// return await del([ "dist/browser/**", "!dist/browser" ], {force:true});
// });
//
gulp.task("default", [ "clean-dist/browser-folder" ]);
Also i used function (){} instead of lambda. Exact same result. WTCrap is happening?
All questions i reaserched plus the docs suggest i'm doing things correctly.
Am i missing something very obvious - i'm just blinded to it right now ? Thanks :)
Crap! i found it. So basically my gulp scripts are in a gulp folder like so (sorry i forgot to mention this in the question - since i wasn't thinking is somehow relevant) :
rootOfProject/gulp/firstGulpScript.js
rootOfProject/gulp/secondGulpScript.js
// and the cleaning path:
rootOfProject/dist/browser/crap.js
I need multiple gulp script files since is a project with multiple apps which require separate compilation in separate locations and such. Seemed nicer to split each app in it's own gulp file. Thinking back at this it might not have been the brightest idea.
Now what happens, in my clean() task to delete crap.js i have :
return del([ "dist/browser/crap.js"], { force : true });
But gulp looks into:
rootOfProject/gulp/dist/browser/crap.js - which of course is wrong location.
I am supposed to write this instead:
return del([ "../dist/browser/crap.js"], { force : true }); - note the ../ in front of the path here. As such the new location will be:
rootOfProject/dist/browser/crap.js - which is the correct location to start cleaning.
There was nothing to clean in rootOfProject/gulp/dist .. that's why i wasn't getting any errors. The task was running just fine, but nothing was beeing deleted form dist/... With no errors things were even more confusing
This hole mess lost me 2-3 hours..
Hopefully if somebody finds an issue like this they will be more careful about the path specified - when the gulp script file is not in the root of the project.

Express server loads html page with/without css/js when last route character is without/with '/', respectively

The following is affecting my second html page model.html:
If my route address is with a '/ at the end (typed on browser addr field) like so: http://localhost:3002/home/model/ then the correct html page is loaded, but no css/js is loaded.
If my route address is without a '/ at the end like so: http://localhost:3002/home/model then the correct html page is loaded, and css/js is loaded.
Without '/' at the end, css/js loads fine using statics/css/style.css and js/dynamicData.js
The weird part is that when '/' is at the end, I can use ../statics/css/style.css to load the css and "../js/chartData.js" to load js - but that means the one without '/' now longer loads the css/js.
My folder structure:
js - has other js scripts
node_modules
statics
css - has style.css
image - has images
index.html
model.html
index.js - init express server
pc_server.js - express server
Express code (pc_server.js)
Middleware setup?:
process.chdir(__dirname);
// base = '/home'
app.use(base, express.static(__dirname));
Routes:
const INDEX_PAGE = '/';
const MODEL_PAGE = '/home/model';
function setupRoutes(app) {
const BASE = app.locals.base;
app.get(INDEX_PAGE, redirectHome(app));
// BASE = '/home'
app.get(BASE, toHomePage(app));
app.get(MODEL_PAGE, toModelPage(app));
Routes functions defined:
function redirectHome(app) {
return errorWrap(async function(req, res) {
try {
res.redirect(app.locals.base);
}
catch (err) {
console.error(err);
}
});
}
function toHomePage(app) {
return errorWrap(async function(req, res) {
try {
res.sendFile(path.join(__dirname+'/statics/index.html'));
}
catch (err) {
console.error(err);
}
});
}
function toModelPage(app) {
return errorWrap(async function(req, res) {
try {
res.sendFile(path.join(__dirname+'/statics/model.html'));
}
catch (err) {
console.error(err);
}
});
}
The goal is to load the same page with css/js with either http://localhost:3002/home/model/ or http://localhost:3002/home/model
Additional: Why is it that when I type http://localhost:3002/home I get http://localhost:3002/home/ automatically on my browser addr field?
the problem
it probably occurs due to relative links in your site.
when home/model is used - relative css/style.css link will lead to home/css/style.css
when home/model/ is used, the same link will lead to home/model/css/style.css
the solution:
the easiest way to solve it is changing your link tag to:
<link rel="stylesheet" type="text/css" href="../../home/statics/css/style.css">
this link goes to the root address, and then enters your path Independently from the user's path.
why it's working?
the ../../ prefix tell the browser to go two levels up.
the browser consider the "home/model/" as a visit inside a model folder inside home folder. two levels upward lead the browser to the root level, where it has a clean start.
when the user visits "home/model", it considered as a file inside the home folder. one level upward is the root level, and the second ../ does nothing.
after achieving the root level - the browser entering "home/statics/css/style.css" and find the right file in both cases :)

gulp and pug - unable to parse nested partials

I am using gulp with gulp-pug so that I can split my template into reusable components. Pug grabs any existing *.pug(jade) files and converts them to generic html files on browser-sync and/or project build (in my case).
gulp.task('views', function buildHTML() {
return gulp.src('src/views/*.pug')
.pipe(changed('src', {
extension: '.html'
}))
.pipe(pug({
pretty: true
}))
.pipe(gulp.dest('src/'))
});
gulp.task('watch', ['browserSync', 'views', 'sass'], function () {
gulp.watch('src/scss/**/*.scss', ['sass']);
gulp.watch('src/views/**/*.pug', ['views']);
// Reloads the browser whenever HTML or JS files change
gulp.watch('src/views/**/*.pug', browserSync.reload);
gulp.watch('src/*.html', browserSync.reload);
gulp.watch('src/js/**/*.js', browserSync.reload);
});
gulp.task('default', function (callback) {
runSequence(['views', 'sass', 'browserSync', 'watch'],
callback
);
});
And this is the basic pug index with included partials
doctype html
html(lang='en')
include partials/head.pug
body
<!-- content -->
include partials/footer.pug
include partials/scripts.pug
Everything is running smoothly except for one thing, my views folder structure is as follows:
views
--- partials
--- *
--- *
--- etc.
--- index
When I make changes in one of my partials (the pug files inside the partials folder) and I save, the live-reload functionality works as expected, but the *.pug files are not being parsed. When I save the index.pug however, files are converted and the page loads the new content.
What am I doing wrong and where?
P.S. Even when editing the index file, I have to manually refresh the page from time to time so it can render the page instead of a blank slate.
A tiny, but big mistake here. I was also live-reloading the pug files, which causes some confusion to the parser.
My watch task looked like this:
gulp.task('watch', ['browserSync', 'views', 'sass'], function () {
gulp.watch('src/scss/**/*.scss', ['sass']);
gulp.watch('src/views/**/*.pug', ['views']);
// Reloads the browser whenever HTML or JS files change
gulp.watch('src/views/**/*.pug', browserSync.reload);
gulp.watch('src/*.html', browserSync.reload);
gulp.watch('src/js/**/*.js', browserSync.reload);
});
Now, I removed this line:
gulp.watch('src/views/**/*.pug', browserSync.reload);
which made no sense, but I found it.
You only need to watch for changes in the html files.