I trying to setting up my gulpfile.js file with features like "scss to css transformation" / watcher / live reload.
// Variables
var gulp = require('gulp');
var plugins = require('gulp-load-plugins')();
var source = './src';
var destination = './dist';
var browserSync = require('browser-sync');
// Server
gulp.task('browserSync', function(){
browserSync.init({
server: {
baseDir: 'src'
}
})
});
// Task build : Scss -> Css
gulp.task('buildCss', function () {
return gulp.src(source + '/assets/styles/*.scss')
.pipe(plugins.sass())
.pipe(plugins.cssbeautify({indent: ' '}))
.pipe(plugins.autoprefixer())
.pipe(gulp.dest(destination + '/assets/styles/'));
});
gulp.task('watch', function () {
gulp.watch(source + '/assets/styles/*.scss', gulp.series('buildCss'));
});
gulp.task('startDev', gulp.series('browserSync', 'watch'));
First, I built the css transformation code, after I did the watcher and it was working well but when I added "browserSync" part, it breaks all.
When I launch "startDev", new tab open so the server is launching i guess, but nothing happen after as you can see on the console here : https://i.stack.imgur.com/u82Jn.png
Do you have any idea where the problem can come from ?
Thanks in advance
Related
I have a wordpress installation and creating a theme based on a lynda.com tutorial (WordPress: Building Themes from Scratch Using Underscores).
I installed gulp and all the needed stuff to work with scss but the problem is sometimes, changes don't save!
http://prntscr.com/o60i1a
the file is changed and watch is starting but the scss file is not updating.
The problem is sometimes it works when I close cmd or browser!
I read in another question here that you need to add this to sublime:
"atomic_save" : true
I did it, and it worked so changes are now saving okay (I was happy) but this mourning it's not saving again : (
Gulpfile.js:
var gulp = require('gulp'),
// Prepare and optimize code etc
autoprefixer = require('autoprefixer'),
browserSync = require('browser-sync').create(),
image = require('gulp-image'),
jshint = require('gulp-jshint'),
postcss = require('gulp-postcss'),
sass = require('gulp-sass'),
sourcemaps = require('gulp-sourcemaps'),
// Only work with new or updated files
newer = require('gulp-newer'),
// Name of working theme folder
root = '../' + themename + '/',
scss = root + 'sass/',
js = root + 'js/',
img = root + 'images/',
languages = root + 'languages/';
// CSS via Sass and Autoprefixer
gulp.task('css', function() {
return gulp.src(scss + '{style.scss,rtl.scss}')
.pipe(sourcemaps.init())
.pipe(sass({
outputStyle: 'expanded',
indentType: 'tab',
indentWidth: '1'
}).on('error', sass.logError))
.pipe(postcss([
autoprefixer('last 2 versions', '> 1%')
]))
.pipe(sourcemaps.write(scss + 'maps'))
.pipe(gulp.dest(root));
});
// Optimize images through gulp-image
gulp.task('images', function() {
return gulp.src(img + 'RAW/**/*.{jpg,JPG,png}')
.pipe(newer(img))
.pipe(image())
.pipe(gulp.dest(img));
});
// JavaScript
gulp.task('javascript', function() {
return gulp.src([js + '*.js'])
.pipe(jshint())
.pipe(jshint.reporter('default'))
.pipe(gulp.dest(js));
});
// Watch everything
gulp.task('watch', function() {
browserSync.init({
open: 'external',
proxy: 'localhost/wp',
port: 8080
});
gulp.watch([root + '**/*.css', root + '**/*.scss' ], ['css']);
gulp.watch(js + '**/*.js', ['javascript']);
gulp.watch(img + 'RAW/**/*.{jpg,JPG,png}', ['images']);
gulp.watch(root + '**/*').on('change', browserSync.reload);
});
// Default task (runs at initiation: gulp --verbose)
gulp.task('default', ['watch']);
Can I get some insight on why I'm getting this message in chrome console, it seems to prevent css code injection.
Browsersync reloading all stylesheets because path
'html\css\theme.css' did not match any specific one.
I suspect it's a path issue i have, but I can't seem to figure it out.
I tried to strip as much as I could.
Here's my folder structure:
/_base/gulpfile.js
/_base/html/index.html
/_base/html/css/theme.css
/_base/src/scss/theme.scss
And here's my code:
// Defining requirements
var gulp = require('gulp');
var plumber = require('gulp-plumber');
var sass = require('gulp-sass');
var watch = require('gulp-watch');
var browserSync = require('browser-sync').create();
var sourcemaps = require('gulp-sourcemaps');
var notify = require('gulp-notify');
// var style lint
//general error handler with plumber
var pb_errorHandler = { errorHandler: notify.onError({
title: 'Gulp',
message: 'Error: <%= error.message %>'
})
};
// stage 1 - HTML CSS JS FILE CREATION
// A. scss to css
var s1_sassOptions = {
errLogToConsole: true,
outputStyle: 'expanded'
};
// compile stage1 scss files, use plumber and sorcemaps.
// to do : need to check what error handling to use - curently 2
gulp.task('create-css', function () {
gulp.src('src/scss/theme.scss')
.pipe(plumber(pb_errorHandler))
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(sass(s1_sassOptions).on('error', sass.logError))
.pipe(sourcemaps.write(undefined, { sourceRoot: null }))
.pipe(gulp.dest('html/css/'))
});
// automatically reloads the page when files coressponding to this paths are changed:
var s1_broswserSync_files = [
'html/css/*.css'
];
// browsersync options
var s1_browserSync_options = {
server:"./html"
};
gulp.task('browser-sync', function() {
browserSync.init(s1_broswserSync_files, s1_browserSync_options );
});
// Starts watcher. Watcher runs gulp sass task on changes
gulp.task('stage1-watch', function () {
gulp.watch(['src/scss/*.scss'], ['create-css']);
});
// Starts watcher with browser-sync. Browser-sync reloads page automatically on your browser
gulp.task('stage1', ['browser-sync', 'stage1-watch'], function () { });
It looks like your options for browserSync.init() aren't correct. The init method takes two optional arguments of configuration options and a callback function. See https://browsersync.io/docs/api#api-init
You want to setup your options like this.
var s1_browserSync_options = {
server:"./html",
files: "html/css/*.css"
};
gulp.task('browser-sync', function() {
browserSync.init(s1_browserSync_options );
});
Take a look at the SASS and CSS injecting in the docs https://browsersync.io/docs/gulp#gulp-reload
Browsersync stream is not working for me.
I've copied example from official documentation and it won't working. Reloading for html and js files working fine. Only sass streaming wouldn't work. I've read all the issues on github and can't find an answer for my question.
var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync');
var useref = require('gulp-useref');
var uglify = require('gulp-uglify');
var gulpIf = require('gulp-if');
var cssnano = require('gulp-cssnano');
var imagemin = require('gulp-imagemin');
var cache = require('gulp-cache');
var del = require('del');
var runSequence = require('run-sequence');
// Development Tasks
// -----------------
gulp.task('serve', ['sass'], function() {
browserSync.init({
server: {
baseDir: "./app",
index: 'index.html'
}
});
gulp.watch('app/styles/*.scss', ['sass']);
gulp.watch("app/*.html").on('change', browserSync.reload);
gulp.watch('app/pages/*.html').on('change', browserSync.reload);
gulp.watch('app/js/**/*.js').on('change', browserSync.reload);
});
// Compile sass into CSS & auto-inject into browsers
gulp.task('sass', function() {
return gulp.src('app/styles/*.scss'). // Gets all files ending with .scss in app/scss and children dirs
pipe(sass().on('error', sass.logError)). // Passes it through a gulp-sass, log errors to console
pipe(gulp.dest('app/css')). // Outputs it in the css folder
pipe(browserSync.stream());
})
// Build Sequences
// ---------------
gulp.task('default', function(callback) {
runSequence([
'sass', 'serve'
], callback)
})
gulp.task('build', function(callback) {
runSequence('clean:dist', 'sass', [
'useref', 'images', 'fonts'
], callback)
})
I would make three quick changes to see if they help. First
const browserSync = require("browser-sync").create();
Note the create() at the end, you need that. Second, simplify this:
gulp.task('default', function(callback) {
runSequence([
'sass', 'serve'
], callback)
})
to:
gulp.task('default', ['serve']);
Your 'serve' task calls the 'sass' task first anyway so you don't need the renSequence stuff. Finally, change:
pipe(browserSync.stream());
to:
pipe(browserSync.reload({stream:true}));
I would also make this change:
gulp.watch('app/js/**/*.js').on('change', browserSync.reload(stream:true}));
The Setup:
Visual Studio 2013 update 5
I am using Task Runner Explorer and the below gulp file from recipes:
'use strict';
var watchify = require('watchify');
var browserify = require('browserify');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var gutil = require('gulp-util');
var assign = require('lodash.assign');
var customOpts = {
entries: ['./app/controller.js'],
debug: true
};
var opts = assign({}, watchify.args, customOpts);
var b = watchify(browserify(opts));
gulp.task('js', bundle); // so you can run `gulp js` to build the file
b.on('update', bundle); // on any dep update, runs the bundler
b.on('log', gutil.log); // output build logs to terminal
function bundle() {
return b.bundle()
// log errors if they happen
.on('error', gutil.log.bind(gutil, 'Browserify Error'))
.pipe(source('bundle.js'))
// optional, remove if you don't need to buffer file contents
.pipe(buffer())
// optional, remove if you dont want sourcemaps
.pipe(sourcemaps.init({ loadMaps: true })) // loads map from browserify file
// Add transformation tasks to the pipeline here.
.pipe(sourcemaps.write('./',{includeContent: false, sourceRoot: '../'})) // writes .map file
.pipe(gulp.dest('./dist'));
}
The below is from the html page containing a reference to my browserify bundled file:
<head>
<title></title>
<script src="Scripts/angular.min.js"></script>
<script src="dist/bundle.js"></script>
</head>
I get the following source Maps and bundle.
SourceMap:
{"version":3,"sources":["node_modules/browserify/node_modules/browser-pack/_prelude.js","app/controller.js","app/module.js"],"names":[],"mappings":"AAAA;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClBA;AACA","file":"bundle.js","sourceRoot":"../"}
Bundle:
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
require('./module.js');
angular
.module('app')
.controller('myController',
function () {
var vm = this;
vm.title = 'test';
activate();
function activate() { }
});
function test() {
var vm = 'test';
}
},{"./module.js":2}],2:[function(require,module,exports){
angular.module('app', []);
},{}]},{},[1])
I can debug successfully using the original files loaded through source maps in IE and chrome.
The Problem:
I cannot debug with script debugger within functions in the source mapped files but I can in the bundled file.
Scripts
Can't Debug in function in controller.js but can debug outside of controller function
Can Debug Bundle.JS
Let me know if you have any suggestions. Chrome and IE debugging works fine but a good percentage of our team debugs in visual studio.
I'm trying to bring a typescript app out of an ASP.NET MVC environment into a seperate app to seperate frontend and backend needs.
The typescript remains unchanged and I tried to compile the typescript with gulp but the code doesn't seem to compile. I followed this blogpost by Dan Wahlin. But the typescript doesn't seem to compile. I'm on a Windows 8.1 laptop with Visual Studio 2015 Premium installed.
The directory structure of my project is as follows:
/
-- App/
---- Controllers/
------ xxController.ts
-- Scripts/
---- typings/
------ xxlibrary/
-------- library.d.ts
---- tsd.d.ts
The files I have are the following:
Gulpfile.config.js:
'use strict';
var GulpConfig = (function () {
function gulpConfig() {
this.source = '/App';
this.tsOutputPath = '/Scripts';
this.allJavaScript = ['/Scripts/**/*.js'];
this.allTypeScript = this.source + '/**/*.ts';
this.typings = '/Scripts/typings';
this.libraryTypeScriptDefinitions = this.typings + '/**/*.ts';
}
return gulpConfig;
})();
module.exports = GulpConfig;
Please note that when I use the './' notation as shown in Dan Wahlin's config gulp gives me an exception:
[11:08:11] Using gulpfile D:\Files\Work\Source\ImageManagement\Imagemanagement.App\Gulpfile.js
[11:08:11] Starting 'ts-lint'...
[11:08:11] Starting 'compile-ts'...
stream.js:94
throw er; // Unhandled stream error in pipe.
^
SyntaxError: Unexpected token
gulpfile.js:
'use strict';
var gulp = require('gulp'),
debug = require('gulp-debug'),
inject = require('gulp-inject'),
tsc = require('gulp-typescript'),
tslint = require('gulp-tslint'),
sourcemaps = require('gulp-sourcemaps'),
del = require('del'),
Config = require('./gulpfile.config'),
tsProject = tsc.createProject('tsconfig.json'),
browserSync = require('browser-sync'),
superstatic = require('superstatic');
var config = new Config();
/**
* Compile TypeScript and include references to library and app .d.ts files.
*/
gulp.task('compile-ts', function () {
var sourceTsFiles = [config.allTypeScript, //path to typescript files
config.libraryTypeScriptDefinitions]; //reference to library .d.ts files
var tsResult = gulp.src(sourceTsFiles)
.pipe(sourcemaps.init())
.pipe(tsc(tsProject));
tsResult.dts.pipe(gulp.dest(config.tsOutputPath));
return tsResult.js
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(config.tsOutputPath));
});
When I run this gulpfile.js there is no error thrown but there is no output in the Scripts as I expect.
[11:15:08] Using gulpfile D:\Files\Work\Source\ImageManagement\Imagemanagement.App\Gulpfile.js
[11:15:08] Starting 'compile-ts'...
[11:15:08] Finished 'compile-ts' after 6.84 ms
Process terminated with code 0.
OK, I found the issue.
When I change this:
'use strict';
var GulpConfig = (function () {
function gulpConfig() {
[...]
this.allTypeScript = this.source + '/**/*.ts';
[...]
this.libraryTypeScriptDefinitions = this.typings + '/**/*.ts';
}
return gulpConfig;
})();
module.exports = GulpConfig;
To
'use strict';
var GulpConfig = (function () {
function gulpConfig() {
[...]
this.allTypeScript = './App/**/*.ts';
[...]
this.libraryTypeScriptDefinitions = './Scripts/typings/**/*.ts';
}
return gulpConfig;
})();
module.exports = GulpConfig;
It works just fine. Not sure why though.