Using Gulp + BrowserSync + Connect PHP for Multiple Projects - javascript

I've put together a boilerplate gulp setup for myself when setting up a new webapp project and I'm having some trouble with using BrowserSync, and Connect-PHP in tandem.
Here's are my tasks for spinning up the server and starting BS:
gulp.task('php', function() {
php.server({base: 'app', port: 8030, keepalive: true});
})
gulp.task('browserSync',['php'], function(){
browserSync.init({
proxy: '127.0.0.1:8030',
port: 8080,
open: true,
notify: false
});
})
The problem is that every time I set up a new project, I have to change the port for the php server and proxy url to a new, previously unused one.
Is there a way I can avoid having to choose a new port number each time?
For further reference, it appears this question was asked before but not answered here: Can't use gulp (with gulp-connect-php and gulp-browser-sync) with multiple projects

Related

Electron + Vue API requests fall to app://

I've built a Vue app and added Electron to it. I used Vue CLI Plugin Electron Builder
It's ok in development mode, all API requests fall on address which is written in my vue.config.js:
proxy: {
'^/api': {
target: 'http://my-api:3000',
changeOrigin: true
},
},
For example, Axios POST request /api/open_session/ falls to http://my-api/api/open_session as needed.
When I build the project it creates an app:// protocol to open the index.html file.
But it also makes all url paths beginning with app:// including API requests.
My background.js:
if (process.env.WEBPACK_DEV_SERVER_URL) {
// Load the url of the dev server if in development mode
await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
if (!process.env.IS_TEST) win.webContents.openDevTools()
}
else {
createProtocol('app');
// Load the index.html when not in development
win.loadURL('app://./index.html');
}
I want these paths to be directed to my API, while open all my files as usual (via app protocol)
Well, it's been a longer time and I coped with that on my own. However, here's an answer I came across some forums for those who are struggling with the same issue:
Firstly, I modified my vue.config.js:
proxy: {
'^/api': {
target: 'http://127.0.0.1:3000',
changeOrigin: true
},
},
Then, I made some changes in main.js - added a session variable:
const sesh = session.defaultSession.webRequest.onBeforeSendHeaders({
urls: ['*://*/*']
}, (details, callback) => {
// eslint-disable-next-line prefer-destructuring
details.requestHeaders.Host = details.url.split('://')[1].split('/')[0]
callback({
requestHeaders: details.requestHeaders
})
})
that defines app's behavior when requests get called. Also, I've added a session value to webPreferences:
const win = new BrowserWindow({
width: 1500,
height: 700,
title: "Title",
webPreferences: {
session: sesh,
nodeIntegration: true,
webSecurity: false
}
})
And, finally, load my index.html via app protocol
createProtocol('app');
win.loadURL('app://./index.html');
In result, all my requests got redirected to my server.
Forgive me for not knowing the source, if the author of the code is reading this, you can surely mark yourself in comments :)

Rewriting Webpack Proxy URLs

I'm using Webpack Dev Server to proxy my files from an external url, that's because I'm using it to develop locally and proxying the PHP/Twig files from the server, so that way I don't need to set up all the back-end locally.
But the problem is that I need to rewrite the assets urls to pull these files from my local machine, not from the proxy. Right now, when I open my localhost, all the assets are being loaded from the server. i.e: http://mycoolwebsite.com/core/somefolder/assets/styles.css
And I need to replace that to pull from my localhost, like this:
/assets/styles.css
This is what I have now:
devServer: {
compress: true,
port: 9000,
proxy: {
'*': {
target: 'http://mycoolwebsite.com',
changeOrigin: true,
secure: false
}
}
Any clue?
Thanks!
you want all request that go to your server "http://mycoolwebsite.com/**"
to go to your local machine: "http://localhost:9000/" (assuming its running on port 9000)
so try this:
proxy: {
'/assets/**': {
target: 'http://localhost:9000',
secure: false,
pathRewrite: function(req, path) {
//use the pathRewrite to modify your path if needed
return path;
}
}
now it shouldn't make any difference what server you are actually calling. every request that includes '/assets/' should go to your localhost. (I can not test it atm)

browser-sync watch not working

So I have a very simple setup, basically straight from browser-syncs docs however no matter what I do, I cannot get it to trigger a change event on watched files. Frustrating.
Here is my code:
var sync = require('browser-sync').create();
sync.watch([
"react/**/*.{js,css,scss,html}",
"static/**/**", "factories/factories.js"
]).on('change', sync.reload);
sync.init({
proxy: 'localhost:8000',
port: 4200,
ghostMode: false,
reloadOnRestart: true,
open: false,
notify: false,
minify: false,
logLevel: "silent"
});
I have another system watching those files just to test, and when I make a change to one - browser-sync does nothing while my other watcher reports a file change. Help?
So it seems BS's watch doesn't read relative paths like react or ./react. Changing the path to __dirname + '/react/**/*.{js,css,scss,html}' worked.

Very slow BrowserSync server startup with Gulp

I'm using BrowserSync in server mode (using its built-in static server) with GulpJS on a local project, and everything seems to be working correctly except that the BrowserSync server is very slow to startup. BrowserSync itself seems to initialize right away when I run Gulp, but it takes about 4 to 5 minutes (and occasionally more) for the server to start and for it to return the access URLs. During this period, everything continues to run and BrowserSync responds to reload() calls and such, but access is not available via the usual URLs (in this case, localhost:3000 and localhost:3001). Once the access URLs are returned, the server has seemingly started and BrowserSync's page refreshes work fine and are actually very speedy.
I have tried several different configurations of my gulpfile.js, trying different ways to initialize BrowserSync, different approaches to calling the stream() and reload() methods (including trying BrowserSync's basic Gulp/SASS "recipe"), and different port numbers, but all configurations had the same problem. I even tried disabling my firewall and AV software (Avast), but nothing.
I'm running Windows 8.1, if that's relevant. BrowserSync is freshly installed locally to the project via NPM, and fresh local installs to other directories have the same problem. NPM, Ruby, Gulp, and all modules seem to be up-to-date. For what it's worth, all of my other experience with Ruby, Gulp, and Node.js have been very smooth and problem-free.
I can't find any other posts mentioning this problem and am beginning to think this is normal behavior. Is this normal, and, if not, does anyone have any ideas of things to try? This delay is not the end of the world since the BrowserSync server does always start (eventually), but it's still a kink in my workflow that I'd rather fix than just deal with.
Finally, here is my gulpfile.js:
/* File: gulpfile.js */
var gulp = require('gulp'),
gutil = require('gulp-util');
jshint = require('gulp-jshint');
sass = require('gulp-sass');
concat = require('gulp-concat');
uglify = require('gulp-uglify');
sourcemaps = require('gulp-sourcemaps');
imagemin = require('gulp-imagemin');
browserSync = require('browser-sync').create();
gulp.task('default', ['watch'], browserSync.reload);
// JSHint
gulp.task('jshint', function() {
return gulp.src('src/js/**/*.js')
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'));
});
// Build JS
gulp.task('build-js', function() {
return gulp.src('src/js/**/*.js')
.pipe(sourcemaps.init())
.pipe(concat('main.js'))
//only uglify if gulp is ran with '--type production'
.pipe(gutil.env.type === 'production' ? uglify() : gutil.noop())
.pipe(sourcemaps.write())
.pipe(gulp.dest('public/www/js/core'));
});
// Build CSS
gulp.task('build-css', function() {
return gulp.src('src/sass/**/*.{sass,scss}')
.pipe(sourcemaps.init())
.pipe(sass()).on('error', handleError)
.pipe(sourcemaps.write()) // Add the map to modified source.
.pipe(gulp.dest('public/www/css/core'))
.pipe(browserSync.stream({match: '**/*.css'}));
});
// ImageMin
gulp.task('imagemin', function () {
return gulp.src('src/img/*')
.pipe(imagemin({
progressive: true,
svgoPlugins: [{removeViewBox: false}]
}))
.pipe(gulp.dest('public/www/img'));
});
// Handle errors
function handleError(err) {
console.log(err.toString());
this.emit('end');
}
// Watch function
gulp.task('watch', function() {
browserSync.init({
server: "./public/www",
//port: 3002
});
gulp.watch('src/js/**/*.js', ['jshint']);
gulp.watch('src/sass/**/*.{sass,scss}', ['build-css']);
gulp.watch('src/js/**/*.js', ['build-js']);
gulp.watch('src/img/*', ['imagemin']);
gulp.watch("public/www/css/**/*.css").on('change', browserSync.reload);
})
The BrowserSync Twitter account suggested that I set the "online" option to true, and...it seems to have worked!
I set it in BrowserSync's init like so:
browserSync.init({
server: "./public/www",
online: true
});
...and the delay is gone!
Going by the BrowserSync docs ( http://www.browsersync.io/docs/options/#option-online ), it seems that setting the online option to true skips the online check. So, I guess that check was somehow what was causing the delay? That seems odd to me, but it's working better now.
In my case I had this code in gulpfile which delay startup about 50 seconds
gulp.watch('./**/*.{js,html}').on('change', browserSync.reload);
and the problem was in the glob string. It inspects even node_modules folder. And I did some changes
gulp.watch(['./scripts/**/*.{js,html}', './index.html'])
.on('change', browserSync.reload);
I think that it is performance feature, that we should more exactly specify glob.

Webpack dev server hot mode not working

Heres my config:
devServer: {
contentBase: '/web/dist/',
hot: true,
stats: {colors: true},
inline: true
}
And here's the gulp task im running:
gulp.task('build', ['clean', 'styles', 'bower', 'media', 'data', 'homepage'], function(done) {
es6promise.polyfill();
console.log('STARTING DEV SERVER...');
server = new WebpackDevServer(webpack(webpackDevConfig), webpackDevConfig.devServer);
server.listen(8080, '0.0.0.0', function (err, stats) {
if (err) {
throw new gutil.PluginError("webpack-dev-server", err);
}
console.log('DEV SERVER STARTED');
done();
});
});
Everything works as expected except the hot loading (no refresh or change when I make changes to files). What am I doing wrong here?
You need to add <script src="http://localhost:8080/webpack-dev-server.js"></script> to your index.html It is not added when you use the API
"Notice that webpack configuration is not passed to WebpackDevServer API, thus devServer option in webpack configuration is not used in this case. Also, there is no inline mode for WebpackDevServer API. <script src="http://localhost:8080/webpack-dev-server.js"></script> should be inserted to HTML page manually."
(http://webpack.github.io/docs/webpack-dev-server.html)
maybe you also need to add 'webpack/hot/dev-server' as an entrypoint to your webpack config
be sure to set
webpackConfig.plugins.push(new webpack.HotModuleReplacementPlugin());
in the webpackConfig as well
If you are using redux can try this.
For some random reason redux-devtools was not allowing hot reload for me. Try removing it from root component and redux compose config.
Note: Use redux devtool browser extension with this config in your store configuration: window.devToolsExtension ? window.devToolsExtension() : f => f
Also, must read: https://medium.com/#rajaraodv/webpacks-hmr-react-hot-loader-the-missing-manual-232336dc0d96#.ejpsmve8f
Or try hot reload 3:
example: https://github.com/gaearon/redux-devtools/commit/64f58b7010a1b2a71ad16716eb37ac1031f93915

Categories