I have successfully written this code and it executes in bash, but doesn't launch the browser. Any help is appreciated.
Both the commented out code and the uncommented launch in bash fine, but I never get chrome to open my html file. How do get chrome to open? Am I missing something?
Toshiba Laptop#ToshibaLaptop MINGW64 ~/Desktop/Projects/trave-site (master)
$ gulp watch
[14:48:50] Using gulpfile ~\Desktop\Projects\trave-site\gulpfile.js
[14:48:50] Starting 'watch'...
[14:48:50] Finished 'watch' after 26 ms
[Browsersync] Access URLs:
-----------------------------------
Local: http://localhost:3000
External: http://10.0.0.235:3000
-----------------------------------
UI: http://localhost:3001
UI External: http://10.0.0.235:3001
-----------------------------------
[Browsersync] Serving files from: ./app
//gulp.task('browser-sync', function() { // this works if uncomented
// browserSync.init({
// server: {
// baseDir: "./"
// }
// });
//});
gulp.task('watch', function(){
browserSync.init({ // this works as well neither launch chrome
server : {
baseDir: "./app",
index: "index.html"
}
});
});
Related
I have created some tasks to recompile the sass with browser-sync whenever changes are made.
My gulp file is as follows:
'use strict';
var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync');
gulp.task('sass', function() {
return gulp.src('./css/*.scss')
.pipe(sass().on('error', sass.logError))
.pipe(gulp.dest('./css'));
});
gulp.task('sass:watch', function() {
gulp.watch('./css/*.scss', ['sass']);
});
gulp.task('browser-sync', function() {
var files = [
'./*.html',
'./css/*.css',
'./img/*.{png,jpg,gif}',
'./js/*.js'
];
browserSync.init(files, {
server: {
baseDir: "./"
}
});
});
gulp.task('default', gulp.series('browser-sync', function() {
gulp.start('sass:watch');
}));
I am using node version 12.16.1, gulp-sass version 4.1.0, gulp-cli version 2.3.0, gulp local version 4.0.2 and browser-sync version 2.26.7.
Change this
// gulp.task('default', gulp.series('browser-sync', function() {
// gulp.start('sass:watch');
// }));
to
gulp.task('default', gulp.series('browser-sync', 'sass:watch'));
I seriously doubt that gulp v4 supports gulp.start.
Also change to this:
gulp.task('browser-sync', function(done) { // added done here
var files = [
'./*.html',
'./css/*.css',
'./img/*.{png,jpg,gif}',
'./js/*.js'
];
browserSync.init(files, {
server: {
baseDir: "./"
}
});
done(); // called done() here
});
When I ran your code I noticed that the sass:watch task was never starting, hence you were not watching any files at all. Here is what you should have seen in your terminal:
[21:26:21] Using gulpfile ~\OneDrive\Test Bed\simple\gulpfile.js
[21:26:21] Starting 'default'...
[21:26:21] Starting 'browser-sync'...
[21:26:21] Finished 'browser-sync' after 164 ms
[21:26:21] Starting 'sass:watch'... // this line missing when running your code
[Browsersync] Access URLs:
-----------------------------------
Local: http://localhost:3000
External: http://10.0.0.186:3000
-----------------------------------
UI: http://localhost:3001
UI External: http://localhost:3001
-----------------------------------
[Browsersync] Serving files from: ./
[Browsersync] Watching files...
Don't be fooled by the last line, browser-sync always spits that out. The reason why the sass:watch task was not starting was because gulp could never get past the browser-sync task - you have to signal gulp somehow that the task has completed and done is one way to do that. Then gulp can go to the next task, which was sass:watch. See gulp: async completion.
You also needed to make the change you noted in your comment gulp.watch('./css/*.scss', gulp.series('scss'));
There is nothing else wrong with your code - it runs perfectly fine for me.
Your Gulpfile isn't watching the sass files when changes are made. It's only looking for CSS changes. This is part of my Gulp task function to look for SCSS file changes
function serve() {
browserSync.init({
open: false,
port: 8000,
server: {
baseDir: 'src/',
index: 'index.html'
},
});
gulp.watch(paths.scss.src, gulp.series([compileSCSS]));
}
And this is my SCSS compile function
function compileSCSS() {
return gulp
.src('./src/scss/style.scss')
.pipe(plugins.rename('style.css'))
.pipe(gulp.dest('./src/css/'));
}
I have prepared a Gulp function with many required tools. You can check here
https://gist.github.com/choyan/ab034dc0539942ee0d8f0ab9788d790f
I have an existing node app. My Node directory structure is setup like this:
./
node_modules/
src/
views/
index.html
...
server.js
test/
gulpfile.js
package.json
I can successfully start my app my running node ./src/server.js from the root shown above. Once started, I can visit "http://localhost:3000" in the browser and see the contents of index.html like I am expecting.
I want to speed up my development and I recently learned about browsersync. In an attempt to include it in my gulp process, I have the following:
var browserSync = require('browser-sync').create();
browserSync.init({
server: {
baseDir: './src/',
server: './src/server.js'
}
});
When I run gulp, I see the following in the command-line:
BS] Access URLs:
--------------------------------------
Local: http://localhost:3000
External: http://[ip address]:3000
--------------------------------------
UI: http://localhost:3001
UI External: http://[ip address]:3001
--------------------------------------
My browser is then opened and it attempts to load http://localhost:3000. At this point, I see the following error in the browser window:
Cannot GET /
What am I doing wrong? I can successfully visit http://localhost:3000 if I start my app using node ./src/server.js, however, its like its not running with BrowserSync. What am I doing wrong?
You already have a node server so i think what you need is Proxy.
And i would also suggest you to use nodemon for going one step ahead in your speed up development thing. It will automatically restart your node development server in case of any changes. So a sample gulpfile in your case(with nodemon) might look like
var gulp = require('gulp');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var nodemon = require('gulp-nodemon');
gulp.task('browser-sync', ['nodemon'], function() {
browserSync.init(null, {
proxy: "http://localhost:3700", // port of node server
});
});
gulp.task('default', ['browser-sync'], function () {
gulp.watch(["./src/views/*.html"], reload);
});
gulp.task('nodemon', function (cb) {
var callbackCalled = false;
return nodemon({script: './src/server.js'}).on('start', function () {
if (!callbackCalled) {
callbackCalled = true;
cb();
}
});
});
~
Why do you want to use the built-in server if you have your own in ./src/server.js ?
Check this, What server in browsersync does is create a static server for basic HTML/JS/CSS websites, so you might need to use the proxy feature as shown here.
This means that you need to run your server as normally and wrap it up in the proxy.
Using the express generator default folder structure with the start script in bin\www, and using the ejs template, this is how i modified my gulpfile.js :
var gulp = require('gulp');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var nodemon = require('gulp-nodemon');
gulp.task('browser-sync', ['nodemon'], function() {
browserSync.init(null, {
proxy: "http://localhost:8000", // port of node server
});
});
gulp.task('default', ['browser-sync'], function () {
gulp.watch(["./views/*.ejs"], reload);
});
gulp.task('nodemon', function (cb) {
var callbackCalled = false;
return nodemon({
script: './bin/www',
env: {
PORT: 8000
}}).on('start', function () {
if (!callbackCalled) {
callbackCalled = true;
cb();
}
});
});
Notice that am watching for any files that end in .ejs. I also got a problem when using nodemon with the port in use, so i added an env to pass the port as 8000,
env: { PORT: 8000 }
Since the tag grunt is missing from the question, here's a solution that works using only NPM (package.json):
"scripts": {
"start": "browser-sync start --serveStatic 'src' --serveStatic 'node_modules' --files 'src'"
}
Now all the <script> src attributes can be relative:
<script src="/stats-js/build/stats.min.js"></script>
I'm trying to set up Gulp to watch 1 thing: server's source. Upon source update, the server node script will start over & client browser will refresh.
I believe I need gulp-nodemon for the server, while browser-sync for the client.
The server's script is executed by: node src\babel.js
The script works when ran that way, but fails through my config for Gulp.
Is there something I am doing wrong?
This is my task script:
var gulp = require('gulp');
var browserSync = require('browser-sync');
var nodemon = require('gulp-nodemon');
gulp.task('default', ['watchServer', 'watchClient']);
gulp.task('watchServer', function() {
gulp.watch('src/**', function () {
nodemon({ // called upon update
script: 'src/babel.js', // I have tried both / & \\
})
});
nodemon({ // called on start
script: 'src/babel.js', // I have tried both / & \\
})
});
gulp.task('watchClient', function() {
browserSync({
open: 'external',
host: '████████',
port: 80,
ui: false,
server: {
// We're serving the src folder as well
// for sass sourcemap linking
baseDir: ['src']
},
files: [
'src/**'
]
});
});
Log:
> gulp
[02:28:04] Using gulpfile B:\Test Server\gulpfile.js
[02:28:04] Starting 'watchServer'...
[02:28:04] Finished 'watchServer' after 19 ms
[02:28:04] Starting 'watchClient'...
[02:28:04] Finished 'watchClient' after 27 ms
[02:28:04] Starting 'default'...
[02:28:04] Finished 'default' after 9.66 μs
[02:28:04] [nodemon] 1.7.1
[02:28:04] [nodemon] to restart at any time, enter `rs`
[02:28:04] [nodemon] watching: *.*
[02:28:04] [nodemon] starting `node src\babel.js`
[BS] Access URLs:
-----------------------------------
Local: http://localhost:80
External: http://████████:80
-----------------------------------
[BS] Serving files from: src
[BS] Watching files...
events.js:141
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE :::80
at Object.exports._errnoException (util.js:837:11)
at exports._exceptionWithHostPort (util.js:860:20)
at Server._listen2 (net.js:1231:14)
at listen (net.js:1267:10)
at Server.listen (net.js:1363:5)
at B:/Test Server/src/app/app.jsx:17:7
at Object.<anonymous> (B:/Test Server/src/app/app.jsx:41:2)
at Module._compile (module.js:434:26)
at normalLoader (B:\Test Server\node_modules\babel-core\lib\api\register\node.js:199:5)
at Object.require.extensions.(anonymous function) [as .jsx] (B:\Test Server\node_modules\babel-core\lib\api\register\node.js:216:7)
[02:28:05] [nodemon] app crashed - waiting for file changes before starting...
You don't need to watch the server file with gulp since nodemon will automatically restart when it changes, try something like this in your config
gulp.task('watchServer', function() {
// remove the gulp.watch entry
nodemon({ // called on start
script: 'src/babel.js', // I have tried both / & \\
ext: 'js',
watch: ['src/babel.js']
})
});
There also seems to be something else running on port 80 (this is the default port for apache) so it might help to change the port browsersync is running on to something like 4000
If your node server is running on let's say port 3000 you will need to proxy it with browsersync for example.
gulp.task('watchClient', function() {
browserSync({
open: 'external',
host: '████████',
proxy: '[YOURHOST]:3000'
port: 4000,
ui: false,
// this entry will most likely need to be removed
// if you are using something like express as a static server
server: {
// We're serving the src folder as well
// for sass sourcemap linking
baseDir: ['src']
},
files: [
'src/**'
]
});
});
I'm trying to debug grunt with Intellij (IDEA).
The technologies are: NodeJS, express, AngularJS.
The problem:
Debugger does not stop on breakpoints.
I'll be happy to hear your thoughts.
configuration tab:
Node interpreter: C:\Program Files\nodejs\node.exe
Javscript file: C:\Users[user]\AppData\Roaming\npm\node_modules\grunt-cli\bin\grunt
Browser / Live Edit tab:
http://localhost:3000/
and here is the Gruntfile.js:
var path = require('path');
module.exports = function (grunt) {
grunt.initConfig({
express: {
dev: {
options: {
script: 'server.js'
}
},
},
watch: {
html: {
files: [ '**/*.html'],
options: {
livereload: true
}
},
server: {
files: [ 'server.js'],
tasks: ['express:dev'],
options: {
livereload: true,
spawn: false // Without this option specified express won't be reloaded
}
},
js: {
files: [ '**/*.js'],
options: {
livereload: true
}
}
},
open: {
express: {
// Gets the port from the connect configuration
path: 'http://localhost:3000'
}
}
});
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-express-server');
grunt.loadNpmTasks('grunt-open');
grunt.registerTask('default', ['express:dev', 'watch' ])
};
Just tried a sample Angular+Express application run as a Grunt task. I've used your Gruntfile.js (unchanged). My Node.js Run configuration looks as fololows:
configuration tab:
Node interpreter: C:\Program Files\nodejs\node.exe
Javscript file: C:\Users[user]\AppData\Roaming\npm\node_modules\grunt-cli\bin\grunt
Working directory: my project root - the folder where Gruntfile.js is located
Live Edit tab:
After launch enabled
with JavaScript Debugger enabled
http://localhost:3000
I set breakpoints in my controllers.js and run the configuration above in debugger => breakpoints in Angular code work as expected. Breakpoints in my server code don't :)
To get breakpoints in server-side code working, I did the following:
added 'debug: true' to dev options in Gruntfile.js:
express: {
dev: {
options: {
script: 'server.js',
debug: true
}
}
},
modified the node_modules\grunt-express-server\tasks\lib\server.js, line 65, changing '--debug' to '--debug-brk=' ('--debug-brk=47977' in my case)
Try installing the JetBrains IDE Support extension for chrome, and then create a javascript Debug configuration like this:
(source: ignaciosuay.com)
My grunt server is running in the port 9000, so change it for 3000.
note: You need to run grunt before running this configuration.
If you have any query, please have a look to this post where is explained step by step how to debug AngularJS with Intellij.
I have written an application in Node.js (with Express & socket.io) and I would like to use Grunt to compile my client-side stuff with livereload while developing and being connected to Node.js application. How can I do this? (Preferably without running Node.js app in another port and client in another port, because of pathing and cross-domain issues)
I installed also Yeoman and it's using out of the box grunt-contrib-livereload package, but from what I understood it's using Node.js Connect server for serving client-side files, thus being separated from my Node.js application..
Example from Gruntfile.js generated by Yeoman:
var lrSnippet = require('grunt-contrib-livereload/lib/utils').livereloadSnippet;
var mountFolder = function (connect, dir) {
return connect.static(require('path').resolve(dir));
};
// ... cut some parts
grunt.initConfig({
watch: {
livereload: {
files: [
'<%= yeoman.app %>/*/*.html',
'{.tmp,<%= yeoman.app %>}/styles/*.css',
'{.tmp,<%= yeoman.app %>}/scripts/*.js',
'<%= yeoman.app %>/images/*.{png,jpg,jpeg}'
],
tasks: ['livereload']
}
// ..cut some parts
},
connect: {
livereload: {
options: {
port: 9000,
middleware: function (connect) {
return [
lrSnippet,
mountFolder(connect, '.tmp'),
mountFolder(connect, 'app')
];
}
}
}
}
// ..cut some parts
});
grunt.registerTask('server', [
'clean:server',
'coffee:dist',
'compass:server',
'livereload-start',
'connect:livereload',
'open',
'watch'
]);
Not sure if you have solved this question yet, but I have done this by adding my express application as a middleware attached to the 'connect.livereload.options.middleware' option.
However, automatic reloading of server side code doesn't work. For that you could implement a reload friendly server using a simple 'node ./server.js', create a connect middleware that acts as a transparent proxy to your development server, and invoke that within your Gruntfile.js before your standard connect/livereload server starts.
connect: {
options: {
port: 9000,
// change this to '0.0.0.0' to access the server from outside
hostname: 'localhost'
},
livereload: {
options: {
middleware: function (connect) {
return [
lrSnippet,
mountFolder(connect, '.tmp'),
mountFolder(connect, 'app'),
require('./server') // your server packaged as a nodejs module
];
}
}
}
}
server.js:
var app = express();
...
// Export your server object.
module.exports = app;
My answer is using Gulp that I am more familiar with, instead of Grunt, but I imagine the same approach would work with Grunt as well.
See my repository (and an older one) and my other answer.
Neither any browser extension nor adding any script to your files is needed.
The solution is based on the gulp-livereload and connect-livereload packages working together. First, you start your live reload listener, and pipe into it any file changes (change * to any more specific node-glob to listen to only specific files):
var gulpLivereload = require('gulp-livereload');
gulpLivereload.listen();
gulp.watch('*', function(file) {
gulp.src(file.path)
.pipe(gulpLivereload());
});
Second, you configure your server to use the listener as middleware via connect-livereload:
var connect = require('connect');
var connectLivereload = require('connect-livereload');
connect()
.use(connectLivereload())
.use(connect.static(__dirname))
.listen(8080);
See the packages for more information on how they work internally.
In the Gruntfile, remove connect:livereload and open from server task.
Add following script in the HTML file
<!-- livereload script -->
<script type="text/javascript">
document.write('<script src="http://'
+ (location.host || 'localhost').split(':')[0]
+ ':35729/livereload.js?snipver=1" type="text/javascript"><\/script>')
</script>