How to setup jade includes with gulp-jade - javascript

I am currently using gulp-jade and I am struggling on how to setup Jade includes in my gulpfile.js.(For clarification, I am referring to this here http://jade-lang.com/reference/includes/) The following is the code in my gulpfile.js
var gulp = require('gulp');
var browserSync = require('browser-sync');
var sass = require('gulp-sass');
var uglify = require('gulp-uglify');
var jade = require('gulp-jade');
var jshint = require('gulp-jshint');
var fileinclude = require('gulp-file-include');
var reload = browserSync.reload;
//compile jade to html
gulp.task('templates', function() {
var YOUR_LOCALS = {};
gulp.src('./app/jade/*.jade')
.pipe(jade({
locals: YOUR_LOCALS
}))
.pipe(gulp.dest('./dist/'))
});
//reload files, once jade compilation happens
gulp.task('jade-watch', ['templates'], reload);
//Sass task for live injecting into all browsers
gulp.task('sass', function () {
gulp.src('./app/scss/*.scss')
.pipe(sass())
.pipe(gulp.dest('./dist/css'))
.pipe(reload({stream: true}));
});
//Separate task for the reaction to js files make change even without compilation and what not
gulp.task('compress', function() {
return gulp.src('./app/js/*.js')
.pipe(uglify())
.pipe(gulp.dest('./dist/js'));
});
gulp.task('js-watch', ['compress'], reload);
//Serve and watch the scss/jade files for changes
gulp.task('default', ['sass', 'templates', 'compress'], function () {
browserSync({server: './dist'});
gulp.watch('./app/**/*.jade', ['jade-watch']);
gulp.watch('./app/scss/*.scss', ['sass']);
gulp.watch('./app/js/*.js', ['js-watch']);
});
I know it is quite a bit to parse through. I am hoping it is a standard something, that won't take too long. If you are interested in seeing the entire file structure, it can be seen at my github here https://github.com/CharlieGreenman/Gulp-with-foundation-and-sass
Thank you, and any help would be more than appreciated!

I wrote a Gulp plugin that simplifies your includes by allowing you to add some arbitrary paths to resolve includes and extends to, so you don't have to worry so much about relative pathing. Take a look: https://github.com/tomlagier/gulp-jade-modules

Turns out it was really simple. There were one thing I was doing wrong
I was using includes ../includes/head instead of include ../includes/head (using includes actually worked for me in grunt, upon further research I saw I was using it wrong for gulp.).

Related

How can I combine these two Gulp tasks into a single one?

Right now I have two tasks: templates and js. templates has to run first so that changes are be picked up by js. I want to combine these, eliminating the intermediate file, so that the task works like this:
Compile and concatenate templates into a single chunk of JS
Concatenate that chunk with the rest of my application's JS code
Output the whole thing as a single file
How can I do this?
Here's my current code:
var gulp = require('gulp');
var handlebars = require('gulp-handlebars');
var concat = require('gulp-concat');
var wrap = require('gulp-wrap');
var declare = require('gulp-declare');
// Compile Handlebars templates into JS
gulp.task('templates', function() {
return gulp.src('./templates/*.hbs')
.pipe(handlebars({
handlebars: require('handlebars')
}))
.pipe(wrap('Handlebars.template(<%= contents %>)'))
.pipe(declare({
namespace: 'templates',
noRedeclare: true,
}))
.pipe(concat('templates.js'))
.pipe(gulp.dest('./js/'));
});
// Concatenate and minify application JS
gulp.task('js', function() {
return gulp.src('./js/*.js')
.pipe(concat('app.js'))
.pipe(gulp.dest('./dist/js'));
For me the easyest and cleaner way is to call one task after the other with
gulp.task('js', ['templates'], function(){
....
In this way the js task need the execution of templates task
Keeping the compilation and the final concat in 2 separate task it's not that bad for me.
Let me know if it's not a viable solution for you
EDIT
in one single task you can try to use merge-stream
and do
var merge = require('merge-stream');
gulp.task('templates', function() {
var jsStream = gulp.src('./js/*.js')
.pipe(concat('all.js'));
var templateStream = gulp.src('./templates/*.hbs')
.pipe(handlebars({
handlebars: require('handlebars')
}))
.pipe(wrap('Handlebars.template(<%= contents %>)'))
.pipe(declare({
namespace: 'templates',
noRedeclare: true,
}))
.pipe(concat('templates.js'));
merge(jsStream, templateStream)
.pipe(concat('app.js'))
.pipe(gulp.dest('./dist/js'));
});
I've done it by heart without trying so my not work as intended

How can I use gulp to replace a string in a file?

I am using gulp to uglify and make ready my javascript files for production. What I have is this code:
var concat = require('gulp-concat');
var del = require('del');
var gulp = require('gulp');
var gzip = require('gulp-gzip');
var less = require('gulp-less');
var minifyCSS = require('gulp-minify-css');
var uglify = require('gulp-uglify');
var js = {
src: [
// more files here
'temp/js/app/appConfig.js',
'temp/js/app/appConstant.js',
// more files here
],
gulp.task('scripts', ['clean-js'], function () {
return gulp.src(js.src).pipe(uglify())
.pipe(concat('js.min.js'))
.pipe(gulp.dest('content/bundles/'))
.pipe(gzip(gzip_options))
.pipe(gulp.dest('content/bundles/'));
});
What I need to do is to replace the string:
dataServer: "http://localhost:3048",
with
dataServer: "http://example.com",
In the file 'temp/js/app/appConstant.js',
I'm looking for some suggestions. For example perhaps I should make a copy of the appConstant.js file, change that (not sure how) and include appConstantEdited.js in the js.src?
But I am not sure with gulp how to make a copy of a file and replace a string inside a file.
Any help you give would be much appreciated.
Gulp streams input, does all transformations, and then streams output. Saving temporary files in between is AFAIK non-idiomatic when using Gulp.
Instead, what you're looking for, is a streaming-way of replacing content. It would be moderately easy to write something yourself, or you could use an existing plugin. For me, gulp-replace has worked quite well.
If you want to do the replacement in all files it's easy to change your task like this:
var replace = require('gulp-replace');
gulp.task('scripts', ['clean-js'], function () {
return gulp.src(js.src)
.pipe(replace(/http:\/\/localhost:\d+/g, 'http://example.com'))
.pipe(uglify())
.pipe(concat('js.min.js'))
.pipe(gulp.dest('content/bundles/'))
.pipe(gzip(gzip_options))
.pipe(gulp.dest('content/bundles/'));
});
You could also do gulp.src just on the files you expect the pattern to be in, and stream them seperately through gulp-replace, merging it with a gulp.src stream of all the other files afterwards.
You may also use module gulp-string-replace which manages with regex, strings or even functions.
Example:
Regex:
var replace = require('gulp-string-replace');
gulp.task('replace_1', function() {
gulp.src(["./config.js"]) // Every file allown.
.pipe(replace(new RegExp('#env#', 'g'), 'production'))
.pipe(gulp.dest('./build/config.js'))
});
String:
gulp.task('replace_1', function() {
gulp.src(["./config.js"]) // Every file allown.
.pipe(replace('environment', 'production'))
.pipe(gulp.dest('./build/config.js'))
});
Function:
gulp.task('replace_1', function() {
gulp.src(["./config.js"]) // Every file allown.
.pipe(replace('environment', function () {
return 'production';
}))
.pipe(gulp.dest('./build/config.js'))
});
I think that the most correct solution is to use the gulp-preprocess module. It will perform the actions you need, depending on the variable PRODUCTION, defined or not defined during the build.
Source code:
/* #ifndef PRODUCTION */
dataServer: "http://localhost:3048",
/* #endif */
/* #ifdef PRODUCTION **
dataServer: "http://example.com",
/* #endif */
Gulpfile:
let preprocess = require('gulp-preprocess');
const preprocOpts = {
PRODUCTION: true
};
gulp.task('scripts', ['clean-js'], function () {
return gulp.src(js.src)
.pipe(preprocess({ context: preprocOpts }))
.pipe(uglify())
.pipe(concat('js.min.js'))
.pipe(gulp.dest('content/bundles/'));
}
This is the best solution because it allows you to control the changes that are made during the build phase.
There I have a versioning specific example for your reference.
let say you have version.ts file and it contains the version code inside it. You now can do as the follows:
gulp.task ('version_up', function () {
gulp.src (["./version.ts"])
.pipe (replace (/(\d+)\.(\d+)(?:\.(\d+))?(?:\-(\w+))?/, process.env.VERSION))
.pipe (gulp.dest ('./'))
});
the above regex works for many situation on any conventional version formats.

gulp tasks sharing a common setting without a global object

I have a number of gulp tasks each residing in its own file (using the require-dir module) rather than a monolithic file.
I am using modules for configuration settings instead of json files (which I prefer for comments and for derived values).
To keep things simple here is an example setup with a single key I need to share/set between the gulp tasks.
/config/index.js
var config = {}
config.buildType = ''; // set this to either 'dev' or 'dist'
module.exports = config;
here is default task for which I want to set config.buildType to 'dev'
default.js
var gulp = require('gulp');
var config = require('../config/');
gulp.task('default', ['build'], function(cb) {
});
here is a deploy task for which I want to set buildType to 'dist'
deploy.js
var gulp = require('gulp');
var config = require('../config/');
gulp.task('deploy-s3', ['build'], function() {
});
here is a build task that I want to change based on buildType
build.js
var gulp = require('gulp');
var runSequence = require('run-sequence');
var config = require('../config/');
gulp.task('build', function(cb) {
console.log('in build',config.buildType);
if (config.buildType == 'dev') runSequence('clean',['sass',config.htmlGenerator], 'watch', cb);
if (config.buildType == 'dist') runSequence('clean',['sass',config.htmlGenerator], cb);
});
So here is the issue If I set config.buildType in default.js or deploy.js outside gulp.task then since they are all lumped into essentially one file by require-dir the value is simply whichever file was loaded last. If I set it inside the gulp.task function I am confused about about the timing/scope of that setting.
Update: Found this related issue https://github.com/gulpjs/gulp/issues/193. It was pointed out in this issue the task function starts after all the queued tasks so that means I can't set something inside the task function and expect it to be executed before the listed tasks (in my case 'build')
one poster made a task to set a parameter like this
gulp.task('set-dist', function () {
config.buildType = 'dist';
});
gulp.task('deploy', ['set-dist', 'build']);
So some advice..... do I go the way of this "hack" or is there some better way to do this??
(fyi, I am just a couple months into learning node/javascript on my own so my experience is limited)
You can use process.env to hold config attributes for your project. Check this.
In your case you can do:
var gulp = require('gulp');
var runSequence = require('run-sequence');
gulp.task('build', function(cb) {
if (process.env.NODE_ENV === 'development') {
runSequence('clean',['sass',config.htmlGenerator], 'watch', cb);
} else {
runSequence('clean',['sass',config.htmlGenerator], cb);
}
});
gulp build NODE_ENV=production for production
or gulp build NODE_ENV=development.
This will play nicely with existing CI tools like Travis.
Decided to go with this dropping the 'build' task altogether. It will hopefully work in some similar form after gulp 4.0 is released. It allows me to modify any setting before calling other tasks. Can use it with gulpif in tasks like my 'sass' task which is a pipe only task. Still wondering if there is a "better" way.
var gulp = require('gulp');
var config = require('../config/');
var runSequence = require('run-sequence');
gulp.task('default', function(cb) {
config.buildType='dev'
config.url = 'http://localhost:' + config.localport;
runSequence('clean',['sass',config.htmlGenerator],'watch', cb);
});

Load HTML Template for use with knockout component via Browserify

I'm using browserify and knockout and am trying to load html files for knockout component templates. I have browserify successfully loading javascript files, but I'm unclear on how to get it to load html files.
I'm trying to do something like this:
(function() {
var ko = require('./lib/knockout/dist/knockout.js');
var authenticationViewModel = require('./viewmodels/authentication.js');
var authenticationView = require('./views/authentication.html');
ko.components.register('authentication', {
template: authenticationView,
viewModel: authenticationViewModel
});
})();
But the template is obviously not loading. Can someone please explain to me how this is to be accomplished?
This is what I have in my gulpfile.js to get browserify to work with .js files:
gulp.task('browserify', function () {
var browserified = transform(function(filename) {
var b = browserify(filename);
return b.bundle();
});
return gulp.src([paths.appJs])
.pipe(browserified)
.pipe(gulp.dest(paths.public));
});
I'm looking into the html-browserify plugin:
https://www.npmjs.com/package/html-browserify
The example they are using looks like this:
gulp.task('js', function() {
gulp.src('js/app.js')
.pipe(browserify({
insertGlobals: true,
transform: html
}))
.pipe(concat('app.js'))
.pipe(gulp.dest('./public/js'));
});
But I'm unclear on how to reconcile this example with my current code that is already working.
brfs should be one option.
In one of my own apps I use gulp to read some template files, combine them into an object, and write a JSON file that I load in my (browserified) app.
I ended up finding and using partialify. It works perfectly for inporting html files as dependencies.
//Gulp Plugins
var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var partialify = require('partialify');
//Browserify
gulp.task('browserify', function() {
return browserify()
.add(paths.browserifyEntry)
.bundle()
.pipe(source('main.js'))
.pipe(gulp.dest(paths.public));
});

Gulp starter kit with gulp-load-plugins

I have a gulp starter kit for my project, however, I want to use gulp-load-plugins to for devDependencies of package.json file. My file structure is
ProjectName
Gulp
-Tasks
-broswerify.js
-browserSync.js
-jade.js
-lint.js
Gulpfile.js
config.json
package.json
Gulpfile.js
var requireDir = require('require-dir');
var dir = requireDir('./gulp/tasks', {recurse: true});
jade.js (Which is working as expected using gulp-load-plugins)
var gulp = require('gulp');
var config = require('../../config.json');
var plugins = require('gulp-load-plugins')();
gulp.task('jade', function(){
return gulp.src(config.jade.src)
.pipe(plugins.jade())
.pipe(gulp.dest(config.jade.build))
});
browsersync.js (which is not working using gulp-load-plugins)
var gulp = require('gulp');
var config = require('../../config.json').browsersync;
var plugins = require('browsersync'); // works
//var plugins = require('gulp-load-plugins')(); // it doesn't works.
gulp.task('browsersync', function () {
plugins.browserSync.init(config); // (browsersync required)
//plugins.browserSync.init(config) it doesn't work. (gulp-load-plugins required)
});
I would like to know that if there is a better way to do that?
Why would you wan't to use gulp-load-plugins if you have a seperate file for each plugin?
This is how i load gulp-load-plugins :
$ = require('gulp-load-plugins')({
pattern: ['gulp-*', 'gulp.*'],
replaceString: /\bgulp[\-.]/,
lazy: true,
camelize: true
}),
Here is an example of a revision plugin:
// revision styles
gulp.task('rev-styles', function () {
return gulp.src(dev.css)
.pipe($.rev())
.pipe($.cssmin())
.pipe(gulp.dest(dist.css))
.pipe($.filesize())
.pipe($.rev.manifest({merge: true}))
.pipe(gulp.dest('./'))
//rev replace
.on('end', function() {
return gulp.src(['./rev-manifest.json', 'dist/*.html'])
.pipe($.revCollector({
replaceReved: true,
dirReplacements: {
'css': 'css'
}
}))
.pipe(gulp.dest(dist.dist))
});
});
As you can see all my pipes are called .pipe($.pluginName()) meaning $ stands for gulp- . If you have a plugin named gulp-name-secondname you call it like this: .pipe($.nameSecondname()) . Top were i require gulp-load-plugins i have camelize set to true . Lazy loading loads only the plugins you use not all of them .
As a side note i strongly recommend not separating plugins in diffrent files but you can modulate them, meaning separating important tasks in separate files like compilation file , optimization file , build file, etc .
This might help you understand gulp file separation better http://macr.ae/article/splitting-gulpfile-multiple-files.html
Careful with gulp-load-plugins because it slows your tasks , for example i run gulp-webserver , when i use it with gulp-load-plugins the task finishes after 200ms versus 20ms if i use it normally. So don't use with everything, play with it see how much performance you lose on each task and prioritize.
I have used gulp-load-plugins but found that it mainly adds complexity and obscures my code. At also makes it harder to understand for people less familiar with Gulp. It looks cleaner and easier to understand to have all modules explicitly declared at the top.

Categories

Resources