I'm following a basic tutorial for Gulp from here and I got stuck on the browser-sync implementation. I have copied the code exactly as it is in the example, however when I run the watch task, even though sass task executes no problem (new version of the css file is created), the browser doesn't want to refresh! Here is my code:
var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync').create();
gulp.task('sass', function() {
return gulp.src('app/scss/**/*.scss') // Gets all files ending with .scss in app/scss
.pipe(sass())
.pipe(gulp.dest('app/css'))
.pipe(browserSync.reload({stream: true}));
});
gulp.task('browserSync', ['sass'], function() {
browserSync.init({
server: {
baseDir: 'app'
},
})
})
gulp.task('watch', ['browserSync'], function() {
gulp.watch('app/scss/**/*.scss', ['sass']);
// Other watchers
});
And here is my index.html
<!doctype html>
<html>
<head>
<title>test</title>
<link href="css/styles.css" rel="stylesheet" type="text/css" />
</head>
<body></body>
</html>
My styles.scss files has only one style:
body {
background: blue;
}
And here is the output from the console window when I update the styles.scss
So I can see that the browser-sync is aware of the change being made, but it doesn't reload the page in the browser. Why is that? I have looked through the comments under the tutorial and no one seemed to face similar issue. I have also seen couple of other tutorials, but none of them works for me. I use latest version of chrome as my default browser, browser-sync version 5.6.0 and gulp version 3.9.1
I've never heard of piping files through browserSync.reload as a way to reload the dev server, and couldn't find any examples of that particular technique in the browserSync documentation. That doesn't necessarily mean that the method is invalid, but maybe the API has changed since CSS-Tricks published their tutorial in 2015? Three years can be an eternity in tooling time.
Anyway, I know I've used Gulp/browserSync/SASS successfully before so I dug up the code relevant to your situation from one of my old gulpfiles.
//watch task
gulp.task('watch', function () {
//spin up dev server
browserSync.init({
server: {
baseDir: "./"
},
});
//when scss files change, run sass task first and reload browserSync second
gulp.watch('./sass/*.scss', ['sass']).on('change', function () {
browserSync.reload();
});
});
//call watch task
gulp.task('default', ['watch']);
Basically when you call the watch task it immediately spins up the development server and then listens for changes to your scss files. When a change is detected, it calls the sass task as a dependency and runs whatever code you have for preprocessing (which you said is currently working in your file). After the sass task is completed, browserSync.reload is called via the .on method.
I haven't used this particular configuration in awhile but let me know if it works and if not I'd be happy to troubleshoot it with you. It's good boilerplate for any dev to have on hand.
EDIT: The above snippet was taken from a much larger gulpfile and upon second inspection I identified some parts that prevented it from working in a standalone context. Edited snippet to correct this.
I am running a MAMP site and this worked for me
//define task
gulp.task('bsync', function () {
//spin up dev server
browserSync.init({
proxy: "dev.sitename.local",
hostname: "dev.sitename.local",
port: 3000, //even if apache is running on 80 or something else
});
//when css files change, reload browserSync
gulp.watch('./css/*.css').on('change', function () {
browserSync.reload();
});
});
//call task with 'gulp runbsync'
gulp.task('runbsync', ['bsync']);
https://gist.github.com/petergus/31d75a5145e062d4eaa42eb04ce23aea
Related
I have been trying to get my node.JS file to serve my HTML app with static CSS and JS files included too but have ran into great difficulties (the HTML file is loading, but with no styling). From my searching it seems the main recommended method is to add the Express middleware to your node.JS and then add this line:
app.use(express.static(path.join(__dirname, 'static/')));
Before I go on too much further I will show you my directory set-up:
-static
-images
-favicon
-favicon.png
-logo.png
-style
-design.css
-theme.css
-w3.css
-source
-client
-style.js
-node_modules
-...
-index.html
-root.js
-package-lock.json
-...
The 'root.js' file is my node.JS file that I am running and it serves the 'index.html' page, but all the CSS and JS files my HTML page links to come up with this sort of error...
The stylesheet http://localhost:8080/static/style/design.css was not loaded because its MIME type, "text/html", is not "text/css".
Here is one example of a line in my 'index.html' where I try to link to that CSS file...
<link rel="stylesheet" type="text/css" href="static/style/design.css">
...and here is where 'index.html' is served in my 'root.js' file...
http.createServer(function (req, res) {
fs.readFile('index.html', function (err, data) {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(data);
return res.end();
});
}).listen(8080);
I am not too sure where I am going wrong as most guides on the topic seem to imply that when I add in the magic '__dirname' line to my node.JS that everything is meant to resolve itself. When I just run my HTML page locally by opening it in Chrome or Firefox it works fine. I am hoping you might be able to explain to me where I am going wrong, thank you.
I'm new with gulp and I hope I explain myself clearly.
I'm using gulp's browser-sync with MAMP to create a WordPress theme. When browser-sync is executed through gulp task, my WordPress site opens under localhost:3000/mytheme but without images because images are inside localhost:8888... What I'm doing wrong?
gulpfile.js is inside my theme folder:
htdocs/wordpress/wp-content/themes/mytheme/gulpfile.js
MAMP settings,
Apache port: 8888 / Nginx port: 8888 / MySQL port: 8889
gulpfile.js
var gulp = require('gulp'),
watch = require('gulp-watch'),
postcss = require('gulp-postcss'),
autoprefixer = require('autoprefixer'),
cssvars = require('postcss-simple-vars'),
nested = require('postcss-nested'),
cssImport = require('postcss-import'),
browserSync = require('browser-sync').create();
gulp.task('style', function(){
return gulp.src('./modules/style/style.css')
.pipe(postcss([cssImport, cssvars, nested, autoprefixer]))
.pipe(gulp.dest('./'));
});
gulp.task('browser-sync', function () {
var files = [
'./*.php',
'./style.css'
];
browserSync.init(files, {
proxy: "localhost:8888/my-theme",
});
});
gulp.task('watch', function(){
watch('./modules/style/**/*.css', function(){
gulp.start('style');
});
});
gulp.task('default', ['style', 'browser-sync', 'watch'], function(){
gulp.watch('./modules/style/**//**.css', ['watch']);
});
Now I can run Mamp/Wordpress with Gulp and here is how I've done...
Firstly I setted up a vhost with Mamp. These tutorials explain well the steps.
http://www.dennisdeacon.com/web-design/virtual-hosts-for-mamp-based-local-web-development-on-macos-sierra/
https://www.taniarascia.com/setting-up-virtual-hosts/
After setting up a virtual host, I could access to my local site via http://localhost/your-theme/ and http://my-theme.test/.
Next, I installed npm and gulp inside a WP theme folder (Node.js is installed globally) as I mentioned in my question. But I'm not sure if it's better to install these tools inside the htdocs folder or inside a WP theme folder. I did inside a theme folder because it seems easier for me.
To run the browser-sync, I used vhost url for proxy.
After this step, I could access to my site via http://localhost:3000/ with browser-sync.
To set up a vhost, I had to prepare a new WP environment with a new database inside Mamp.
Once a site is opend via localhost:8888, I could not reopen via vhost url. The site is redirected to the localhost:8888 url.
Now I can access to my site (front page) via http://localhost:3000/, but once I go to another pages, my site is redirected to http://localhost/your-theme/another-page and not http://localhost:3000/another-page. That means I can't run browser-sync task outside the front page and I don't know what is the solution...
I've built a gulp project that allows me to build and watch a wordpress theme (bones) in a wordpress installation that is outside the working folder:
Working folder: localhost/sites/testbed/
- dev-bones
- node_modules
- gulpfile.js
- package.json
- package-lock.json
Target folder: localhost/sites/my-wordpress-site/wp-content/themes/
- bones
I installed 'del' and 'run-sequence' so that I could delete the target folder before the build sequence began.
del task:
gulp.task('clean:dirbuild', function() {
// If build directory is outside the working folder:
return del.sync(dir.build, {force: true});
// If inside:
// return del.sync(dir.build);
});
build task:
gulp.task('build', function (callback) {
runSequence('clean:dirbuild',
['php', 'css', 'js', 'copyroot', 'copytranslation'],
callback
)
});
default task:
gulp.task('default', ['build', 'watch']);
After typing 'gulp watch' the browser launches and the wordpress site loads. But I get a white screen with a message saying that the path to bones.php doesn't exist.
I checked the target folder and it does exist.
After scratching my head for a while I manually refreshed the browser and the site loaded correctly.
I've gone through a number of permutations of the code above, always with the same result.
I found this post here on Stack Overflow : run-sequence doesn't run gulp tasks in order, but it didn't seem to fit my case.
I've uploaded the full gulpfile to Github.
I'd be very grateful if someone could give it the once-over and see where I'm going wrong.
UPDATE
I went back to a tutorial I got the 'del' task from. In the comments the author had pointed out that he'd missed something from the task: the callback.
So I updated the code:
gulp.task('clean:dirbuild', function(callback) {
// If build directory is outside the working folder:
return del.sync(dir.build, {force: true}, callback);
// If inside:
// return del.sync(dir.build, callback);
});
and typed 'gulp'.
This time all I got was a white screen and manually refreshing didn't load the site.
OK I figured it out. The problem was with the order of execution of the 'default' task: some of the 'watch' tasks where firing before, during and after the 'build' task.
So I left everything as it was except I changed:
default task
gulp.task('default', ['build', 'watch']);
to
gulp.task('default', function (callback) {
runSequence('build', ['watch'], callback)
});
which ensures that the 'watch' task will run after the 'build' task.
Now, everything works as expected.
Note: I've deleted the example gulpfile.js from GitHub. When I've completed my project and got it on GitHub I'll post a link to it from here.
I am getting started with Angular2.0. I have been following the 5 Min Quickstart and everything works fine although I am using grunt to compile my Typescript and some Sass etc.
I just have one problem I cant solve by myself. I want to move all the public files (generated Javascript and production node modules into a subdirectory. I need to have that, because I run different applications unter the same domian. The frontend depends on the user type that logged in. (backend is written with phalcon)
This is my public folder (the webserver's root)
So the whole Angular applications should live inside the "talent" directory.
The "index.html" contains the following:
<script type="text/javascript" src="/talent/node_modules/systemjs/dist/system.src.js"></script>
<script type="text/javascript" src="/talent/node_modules/angular2/bundles/angular2.dev.js"></script>
<script>
System.config({
baseURL: '/talent',
packages: {'app': {defaultExtension: 'js',}}
});
System.import('app/app');
</script>
SystemJs is able to load my app.js file correctly but then trys to import angular2:
import {bootstrap, Component} from 'angular2/angular2';
Corresponding Javascript:
var angular2_1 = require('angular2/angular2');
This sends a request to http://example.dev/talent/angular2/angular2 resulting in an 404 error.
When I move the node_modules folder and the app folder to the webserver's root and remove baseURL: '/talent' it works just fine.
Here are the requests made for both the working solution (everything at root) and the not working part (everything under /talent)
Working:
Not working:
Can you help me getting this to work?
Had this exact same problem, and just figured it out after several hours. The System config baseURL needs to be set BEFORE angular2.dev.js is loaded. This is because the System.register calls need to be aware of the baseURL at the time of registrations.
e.g.
System.config({ baseURL: '/talent' });
A cleaner way is to just add System.config({ baseURL: '/talent' }) to the very bottom of the system.src.js file.
You can set paths for each library :
System.paths = {
'angular2/*': '/talent/node_modules/angular2/*',
'app/*': '/talent/app/*'
};
Does this work for you?
'angular2/angular2' has been deprecated. Your code should reference 'angular2/core' or the appropriate module for your imports.
You should also not need to specify the path for the angular2 imports in your System.config as System will load them in from the <script> tag you have in the HTML.
You are most likely receiving the 404 error because the angular2.dev.js file is loading 'angular2/core', 'angular2/common', 'angular2/platform/browser', etc... and you are referencing 'angular2/angular2' which is not being registered and therefor SystemJS is attempting to go out and find it.
Change all of your import {...} from 'angular2/angular2' to the correct module import as well. You can find these on the API Preview page of angular.io, or hopefully your IDE will find it for you.
I don't know which version of Angular2 you use but now with beta versions you should use these Angular2 modules:
import {bootstrap} from 'angular2/platform/browser';
import {Component} from 'angular2/core';
Then you need to configure SystemJS as described below:
<script>
System.config({
map: {
app: 'talent/app'
},
packages: {
app: {
format: 'register',
defaultExtension: 'js'
}
}
});
System.import('app/boot')
.then(null, console.error.bind(console));
</script>
With this configuration, when trying to load the app/boot module, SystemJS will load the talent/app/boot.js file that was compiled before from the talent/app/boot.ts file. This behavior applies to all elements under the app module but not to other ones.
Modules like angular2/* will be found from files talent/node_modules/angular2/bundles/[something].js you included using <script> tags.
I made some tests and this configuration works for me ;-)
Thierry
I stumbled upon this question when trying to move from a local (dev) environment to a hosted server (CentOS) where the deployed URLs were all different to my local host. If you're in this situation and the accepted answer doesn't solve your problem (I was already importing the updated imports with Angular2 Beta 15) and using baseURL messes other things up (as it did in my situation) then use:
map: {
app: 'path/to/app/folder'
},
I saw this here and it worked for me (even though it was originally answering a MAMP environment question): Troubles with importing classes from Angular 2 modules with Typescript 1.7
Here's what worked for us:
Make the base ref point to the subdirectory containing the angular project. This will ensure that all the node_module dependencies are found, etc.
Configure the PathLocationStrategy with a different APP_BASE_HREF so that html5 mode still works for the actual angular app.
bootstrap(AppComponent, [..... bind(APP_BASE_HREF).toValue("/yardmap/planning")
ref: https://angular.io/docs/ts/latest/api/common/index/APP_BASE_HREF-let.html
ref: https://angular.io/docs/ts/latest/guide/router.html
base href
Most routing applications should add a element to the index.html as the first child in the tag to tell the router how to compose navigation URLs.
<!DOCTYPE html>
<html>
<head lang="en">
<base href="/talent/">
......
</head>
I'm trying to use gruntjs livereload with a wordpress theme development.
For WP theme development I would normally use MAMP and view the site at localhost in the browser.
If I'm using grunt to create a server do I still need MAMP running.
Do I still need the wordpress folder in the MAMP root folder to connect to the database.
I'm using this simple gruntfile.js that is in the root of the wordpress folder but if I run grunt the browser loads but loads a search engine searching for 0.0.0.0
'use strict';
module.exports = function(grunt){
require('load-grunt-tasks')(grunt);
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
connect: {
options: {
port: 9000,
},
livereload: {
options: {
open: true,
}
}
}
});
grunt.registerTask('default', ['connect']);
}
Is it possible to use grunt livereload with Wordpress without using MAMP.
I've been trying to work this out all day - any help would be greatly appreicated.
Hey so I was also running into this issue and I couldn't get it to work? I feel it has something to do with the fact that MAMP runs your PHP server on a different port. Perhaps you can make your default to port 35729 because that's where the script lives
A really hackish workaround I did was I created a little PHP script that inserts itself when on localhost. I also check to make sure a variable is declared.
livereload.php
<?php
// Live reload script added only on localhost and if $livereload set to true
// add specific whitelist options
$whitelist = array(
'127.0.0.1',
'::1',
'localhost'
);
if(in_array($_SERVER['REMOTE_ADDR'], $whitelist) && isset($livereload)){
echo '<script src="http://localhost:35729/livereload.js?snipver=1"></script>';
}
?>
In my main PHP file, I would do something like
index.php
<?php
$livereload = true;
?>
// Markup, content
<?php
include_once('livereload.php');
?>
Hope this helps.
I'm not sure I understood your problem completely, but you won't be able to run wordpress on "grunt" server, cause node server is in JS and does not support PHP nor mysql (out of the box at least), i can help you to have a working mamp + watch setup
so to have a proper setup including mamp and grunt taking your example as a basis
'use strict';
module.exports = function(grunt){
require('load-grunt-tasks')(grunt);
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
watch: {
options: {
livereload: true,
},
files: {
files: ['theDirYouWantToReload/*.scss'], // or whaterver globbing pattern you would need
tasks: ['yourNeededTask'],
},
}
});
grunt.registerTask('default', ['watch']);
}
you should have a look at grunt-watch-repo for additional information on how watch and reload works.
this was the grunt part, on the WP side you should add the livereload script to your pages
2 solution here, use the browser's extension of LR, and activate it on the browser when you look at these pages, or add the live reload script to WP enqueue
the default address of the script is http://localhost:35729/livereload.js?snipver=1
this is a barebone example, you can fine grain actions on the watch task.