Using Gulp's browser-sync with MAMP in localhost testing environment - browser

I have searched around but no posts pinpointed the pitholes to avoid when using Gulp's BrowserSync with a localhost testing environment. So here is this post.
I am using gulp browser-sync, doing testing with MAMP. Right now I cannot get my browser-sync watch to work. I want to reload browser whenever I save my files.
Under MAMP settings,
Apache port: 80
Nginx port: 80
MySQL port: 3306
gulpfile.js
var gulp = require('gulp');
var browserSync = require('browser-sync'); // create a browser sync instance.
//tasks for development
// Start browserSync server
gulp.task('browserSync', function() {
browserSync({
server: {
baseDir: "app"
},
proxy: "localhost:8080" // can be [virtual host, sub-directory, localhost with port]
});
gulp.task('watch', ['browserSync'], function () {
gulp.watch('app/*.{php,css,js}', browserSync.reload);
});
Since we are talking about MAMP here, my directory is in htdocs/test as shown below:
Also, my index.php file is inside /app
I am thinking I have made mistakes on many levels but right now any combination of my solutions doesnt seem to help and Ive spent hours on this. Any suggestions?

Finally got it to work.
var gulp = require('gulp');
var browserSync = require('browser-sync').create();
gulp.task('default', function() {
browserSync.init({
proxy: "http://localhost/test/app"
});
gulp.watch("./app/*.php").on("change", browserSync.reload);
});
Few things to look out for that the documentation might not explicitly mention:
Do not miss out .create and .init() as we are referring to an instance here.
If you are using some test local server like MAMP, be careful to use 'proxy' instead of 'server'.
Note the URL address I am using refers to the position of the index.php
Lastly, '.on("change", browserSync.reload)' to RELOAD on CHANGE.
Hope my day spent on this saved you some time.

I was struggling with this and found an updated solution that works w/ both MAMP and custom local dev proxies.
In the gulpfile.js gulp.task( 'browser-sync', function() block I removed:
browserSync.init( cfg.browserSyncWatchFiles, cfg.browserSyncOptions );
and replaced with
browserSync.init({
proxy: "your/local/dev/url/here"
});
Hope that saves someone some time!

Related

changing port not working in vuejs project

I have made a sample app in vuejs and try to change the port number. However this seems not to work as I get connection refused on that particular port, like nothing is being served on that port.
So I made a vue.config.js file in the root of my vuejs project.
This config file looks like this:
const BundleTracker = require("webpack-bundle-tracker");
module.exports = {
outputDir: './dist/',
chainWebpack: config => {
config.optimization
.splitChunks(false)
config
.plugin('BundleTracker')
.use(BundleTracker, [{filename: '../frontend/webpack-stats.json'}])
config.resolve.alias
.set('__STATIC__', 'static')
config.devServer
.public('http://0.0.0.0:8080')
.host('0.0.0.0')
.port(8080)
.hotOnly(true)
.watchOptions({poll: 1000})
.https(false)
.headers({"Access-Control-Allow-Origin": ["\*"]})
}
};
When I do 'npm run serve', I get the following:
App running at:
- Local: http://localhost:21739/
- Network: http://0.0.0.0:8080/
Note that the development build is not optimized.
To create a production build, run npm run build.
The port at 21739 is working but the one at 8080 is not working?
Does anyone have any idea what I am doing wrong here, or did I forget something?
Found a somewhat hacky fix. In node_modules/#vue/cli-service/lib/commands/serve.js there is this line that defines the port it is like:
const port = await portfinder.getPortPromise()
I have changed it to
const port = args.port || process.env.PORT || projectDevServerOptions.port
Now everything loads well. Don't know why they choose that approach and if there is a better way to handle this i'd like to know.

Gulp: Trouble setting browserSync and Watch

I'm learning Gulp and NPM and decided to test myself by using Browser-Sync with a PHP project I'm working on (using XAMPP). I know Browser-Sync doesnt work with PHP files, but I wanted to use it with my .css files (and later on perhaps add Sass).
I installed npm, Gulp, Gulp-watch and Browser Sync to my project's root directory and all seemed fine.
I then created a gulp.js file with the following:
var gulp = require('gulp'),
watch = require('gulp-watch'),
browserSync = require('browser-sync').create();
gulp.task('watch', function() {
browserSync.init({
server: {
baseDir: "./"
}
});
watch('css/*.css', function() {
browserSync.reload();
});
});
However, when I gulp watch a new browser window does open but just shows the Cannot GET / error.
Also, the URL shows http://localhost:3002/ rather than http://localhost:myproejct
I read this may have something to do with my baseDir so tried:
baseDir: ""
baseDir: "./"
baseDir: "../myproject"
Would anyone know what I've done wrong?
You are doing way more than is necessary to do what you want. You can just use browsersync as a proxy layer over the top of your hosted site.
See the following example from the docs
# Proxy a PHP app + serve static files & watch them
$ browser-sync start --proxy 'mylocal.dev' --serveStatic 'public' --files 'public'
I think this is what you will need, run it from the physical root of your site and replace mylocal.dev with your php server address
npm install browser-sync -g
browser-sync start --proxy 'mylocal.dev' --serveStatic 'css' --files 'css/*.css'
Your code works fine for me. Assuming your target HTML file works if opened in the browser manually: One common cause of the Cannot Get/ error is using an index file other than Browsersync's default expectation, index.html. Could that be the problem you're having? If you need a custom index file, you can set the index option:
browserSync.init({
server: {
baseDir: 'mybasedirectorypath',
index: 'notindex.html'
}
});
Fwiw, you can also do this more efficiently, and save yourself the weight of installing gulp-watch (this example adapted and simplified from this Browsersync docs example):
var gulp = require('gulp'),
browserSync = require('browser-sync').create();
gulp.task('watch', function() {
browserSync.init({
server: {
baseDir: './'
}
});
gulp.watch('css/*.css').on('change',browserSync.reload)
});
As for using a custom url, check out https://github.com/BrowserSync/browser-sync/issues/646 which has some solutions.

Make gulp.js open non-default browser

The title pretty much says it all. I'm on Windows 10, and I have a node app that I start with npm start. (I know almost nothing about node.js.) The app runs on gulp.js. I need the app to open in Firefox, even though Chrome is my default browser. How can I do this? Here's the code that opens the app now; the docs don't allude to there being such an option for the open parameter:
gulp.task('webserver', function() {
gulp.src('./app')
.pipe(webserver({
livereload: true,
open: true,
defaultFile: 'index.html',
port: serverPort
}));
});
Install gulp-open by typing the following in to your console
npm install gulp-open --save
Add the following to the top of your gulpfile.js
var open = require('gulp-open');
Add the following to the end of your gulpfile.js
gulp.task('browser', function(){
var options = {
uri: 'localhost:<enter the port you are using here>',
app: 'firefox'
};
gulp.src(__filename)
.pipe(open(options));
});
Add 'browser' to your gulp default. This is what actually opens the browser at the port you are running your app on
gulp.task('default', ['webserver', 'browser']);
in console type gulp

How to setup gulp browser-sync for a node / react project that uses dynamic url routing

I am trying to add BrowserSync to my react.js node project. My problem is that my project manages the url routing, listening port and mongoose connection through the server.js file so obviously when I run a browser-sync task and check the localhost url http://localhost:3000 I get a Cannot GET /.
Is there a way to force browser-sync to use my server.js file? Should I be using a secondary nodemon server or something (and if i do how can the cross-browser syncing work)? I am really lost and all the examples I have seen add more confusion. Help!!
gulp.task('browser-sync', function() {
browserSync({
server: {
baseDir: "./"
},
files: [
'static/**/*.*',
'!static/js/bundle.js'
],
});
});
We had a similar issue that we were able to fix by using proxy-middleware(https://www.npmjs.com/package/proxy-middleware). BrowserSync lets you add middleware so you can process each request. Here is a trimmed down example of what we were doing:
var proxy = require('proxy-middleware');
var url = require('url');
// the base url where to forward the requests
var proxyOptions = url.parse('https://appserver:8080/api');
// Which route browserSync should forward to the gateway
proxyOptions.route = '/api'
// so an ajax request to browserSync http://localhost:3000/api/users would be
// sent via proxy to http://appserver:8080/api/users while letting any requests
// that don't have /api at the beginning of the path fall back to the default behavior.
browserSync({
// other browserSync options
// ....
server: {
middleware: [
// proxy /api requests to api gateway
proxy(proxyOptions)
]
}
});
The cool thing about this is that you can change where the proxy is pointed, so you can test against different environments. One thing to note is that all of our routes start with /api which makes this approach a lot easier. It would be a little more tricky to pick and choose which routes to proxy but hopefully the example above will give you a good starting point.
The other option would be to use CORS, but if you aren't dealing with that in production it may not be worth messing with for your dev environment.

Unable to get connect-livereload to work with express server in gulp task

I am working off of Yeoman's gulp-webapp generator. I have modified my gulp serve task to use my Express server, rather than the default connect server it ships with. My issue is with Livereload functionality. I am trying to simply port the connect-livereload to work with my Express server rather than having to install new dependencies. It's to my understanding that most connect middleware should work fine with Express, so I am assuming connect livereload is compatible with Express 4.
Here are the contents of the relevant tasks in my gulpfile:
gulp.task('express', function() {
var serveStatic = require('serve-static');
var app = require('./server/app');
app.use(require('connect-livereload')({port: 35729}))
.use(serveStatic('.tmp'));
app.listen(3000);
});
gulp.task('watch', ['express'], function () {
$.livereload.listen();
// watch for changes
gulp.watch([
'app/*.ejs',
'.tmp/styles/**/*.css',
'app/scripts/**/*.js',
'app/images/**/*'
]).on('change', $.livereload.changed);
gulp.watch('app/styles/**/*.css', ['styles']);
gulp.watch('bower.json', ['wiredep']);
});
gulp.task('styles', function () {
return gulp.src('app/styles/main.css')
.pipe($.autoprefixer({browsers: ['last 1 version']}))
.pipe(gulp.dest('.tmp/styles'));
});
gulp.task('serve', ['express', 'watch'], function () {
require('opn')('http://localhost:3000');
});
With this simple setup, when I run gulp serve in my cmd everything spins up fine and I can accept requests at http://localhost:3000.
Now if I go and change the body's background color from #fafafa to #f00 in main.css and hit save, my gulp output will respond with main.css was reloaded, as seen in the bottom of this screenshot.
However, my webpage does not update. The background color is still light-grey instead of red.
Is there perhaps a conflict between my express server config and the way gulp handles its files? Is my Express server forcing the use of app/styles/main.css rather than the use of .tmp/styles/main.css? Shouldn't the livereload script handle the injection of the new temporary file?
Thanks for any help.
EDIT:
I was able to move forward a bit by adding livereload.js to the script block of my index file, like so:
<script src="http://localhost:35729/livereload.js"></script>
I am now able to get live changes pushed to the client. Why was this file not getting injected before? How can I ensure this is getting used programatically as opposed to pasting it into my files?
I was able to get past this issue by removing the app.use(require('connect-livereload')({port: 35729})) from my gulpfile, along with a couple of other lines, and having that instantiate in my Express server's app.js file.
My gulpfile's express task now looks like this:
gulp.task('express', function() {
var app = require('./server/app');
app.listen(3000);
});
I added in the connect-livereload just above where I specify my static directory in Express:
if (app.get('env') === 'development') {
app.use(require('connect-livereload')());
}
app.use(express.static(path.join(__dirname, '../app')));
Once I started using this setup, I was getting the livereload.js script injected into my document, and client-side changes are now auto-refreshed just how I wanted.
Hope this helps someone!

Resources