I'm using browsersync.reload() when bundling is done. At first time, it worked well but after App is grew bigger, web page failed to load JavaScript on reload with this message:
GET http://localhost:4000/js/bundle.js net::ERR_CONTENT_LENGTH_MISMATCH
This is my gulpfile.js code:
function serve() {
let serverStarted = false;
nodemon({ script: 'server.js' })
.on('start', () => {
if(!serverStarted) {
serverStarted = true;
browserSync.init(null, {
proxy: `localhost:${config.port || 3000}`,
port: config.proxyPort || 4000
});
gulp.watch(`${SRC_DIR}/html/**`, buildHtml);
gulp.watch(`${SRC_DIR}/scss/**`, buildScss);
gulp.watch(`${BUILD_DIR}/html/index.html`).on('change', browserSync.reload);
// return empty stream
return gutil.noop();
}
});
}
I'm using browser-sync with express, so I used proxy. Below code is bundling part for script:
function buildJs() {
const b = persistify()
.add(`${SRC_DIR}/js/index.js`)
.on('update', bundle)
.on('log', gutil.log)
function bundle() {
let stream = b.bundle()
.on('error', swallowError)
.on('end', () => {
gutil.log(`Building JS:bundle done.`);
browserSync.reload();
})
.pipe(source('bundle.js'));
return stream.pipe(gulp.dest(`${BUILD_DIR}/js`));
}
return bundle();
}
I'm using persistify for fast builds, it works with watchify, so I didn't used watch. As you can see the 'end' event, which fires when bundling is done, I invoked browerSync.reload to reload the page.
Reloading itself is not a problem, but it fails load JavaScript as I title said.
Does persistify triggered end event so earlier? or is that somekind of issue from express/browser-sync?
Only I can guess is that end event was fired but stream is still writing the file, so actual file size is not correct and refuse to get.
Intentionally I gave some delays before browsersync.reload(), it works but I don't wanna do this.
Is there a something that I missed? Or am I did wrong approach? Any advice will very appreciate.
I was solving this problem by executing transpiling JavaScript after browser-sync started.
I still don't know why that was happen but it seems script was transpiling and browser try to access while it is still working.