browser sync with ejs, the proxy just loads - node.js

I'm trying to get my MEAN application to work with browser sync.
I'm using .ejs file as template, but whenever I click to open the index.ejs file it downloads it.
I tried this two settings in my gulpfile, but none of them works.
//this downloads the ejs file
gulp.task('serve', function () {
browsersync.init({
server: {
baseDir: [''],
directory: true
}
});
});
//this just loads and I can't access localhost
gulp.task('serve', function () {
browsersync.init({
proxy: 'http://localhost:3000'
});
});
there is a npm package called browser-sync-ejs, but the documentation is non existent and I have no idea how to use it.

Related

File serve in shopify app dev not working

I've created shopify app with node.js app template
npm init #shopify/app#latest
Folder structure is at the bottom
And run npm run dev
It's ok for api endpoints.
What I wanna do is to serve static files. In fact, this is an express.js server and I created a static folder in web folder
app.use(serveStatic('static'));
But I can't access static files. I tried app.use(serveStatic("${process.cwd()}/static")). The above stuff is working on a normal express.js project. But it does not work with shopify cli and vite config.
Vite config is
const config = {
test: {
globals: true,
exclude: ["./frontend/**", "./node_modules/**"],
},
};
export default config;
I finally got it.
I noticed that:
It works if you were to load using localhost:PORT/path/to/static.file. You can print out PORT in your web/index.js.
This simple middleware doesn't get triggered when requesting your static file through ngrok but it does get triggered by number 1 above.
app.use((req, res, next) => {
console.log("Backend hit!");
next();
});
That means the backend never got the static file request. My understanding is vite receives all the requests then proxies some of them to the backend using a config.
The config Shopify gave is not proxying the static file request so you'll need to modify the proxy config.
vite.config
...
export default defineConfig({
...
server: {
host: "localhost",
port: process.env.FRONTEND_PORT,
hmr: hmrConfig,
proxy: {
"^/(\\?.*)?$": proxyOptions,
"^/api(/|(\\?.*)?$)": proxyOptions,
// The next line is what I added
"^/static/.*$": proxyOptions,
},
},
});
web/index.js
app.use("/static", express.static(`${process.cwd()}/public`));
I'm mounting my static files on "/static" but feel free to modify the proxy line to suit your needs.

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

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!

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

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