I'm creating a yeoman generator to make a simple scaffolding for projects.
I would like to include sass bootstrap in the project.
How do I include sass bootstrap to be injected.
I have the following index.js to create the folder and file structures form
files in the templates folder.
This exmaple uses sass files but I would like to include sass bootstrap and I would then change the file structure.
'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var yosay = require('yosay');
var chalk = require('chalk');
var WordpresscdGenerator = yeoman.generators.Base.extend({
init: function () {
this.pkg = require('../package.json');
this.on('end', function () {
if (!this.options['skip-install']) {
this.installDependencies({
//install sass bootstrap
});
}
});
},
promptUser: function(){
var done = this.async();
console.log(this.yeoman);
var prompts = [{
name: 'appName',
message: 'What is the app called ?'
}];
this.prompt(prompts, function(props){
this.appName = props.appName;
done();
}.bind(this));
},
scaffoldFolder: function(){
this.mkdir('wp-content/themes/dist-theme');
this.mkdir('wp-content/themes/dev-theme');
this.mkdir('wp-content/themes/dev-theme/css');
this.mkdir('wp-content/themes/dev-theme/css/scss');
this.mkdir('wp-content/themes/dev-theme/fonts');
this.mkdir('wp-content/themes/dev-theme/images');
this.mkdir('wp-content/themes/dev-theme/js');
},
copyMainFiles: function(){
this.copy('_gruntfile.js', 'wp-content/themes/gruntfile.js');
this.copy('_package.json', 'wp-content/themes/package.json');
this.copy('_bower.json', 'wp-content/themes/bower.json');
//
this.copy('_base_defaults.scss','wp-content/themes/dev-theme/css/scss/_base_defaults.scss');
this.copy('_base_mixins.scss','wp-content/themes/dev-theme/css/scss/_base_mixins.scss');
this.copy('_base_reset.scss','wp-content/themes/dev-theme/css/scss/_base_reset.scss');
this.copy('_config.scss','wp-content/themes/dev-theme/css/scss/_config.scss');
this.copy('_main.scss','wp-content/themes/dev-theme/css/scss/_main.scss');
this.copy('styles.scss','wp-content/themes/dev-theme/css/scss/styles.scss');
this.copy('styles.css','wp-content/themes/dev-theme/css/styles.css');
this.copy('style.css','wp-content/themes/dev-theme/style.css');
this.copy('base.js','wp-content/themes/dev-theme/js/base.js');
this.copy('screenshot.png','wp-content/themes/dev-theme/screenshot.png');
this.copy('index.php', 'wp-content/themes/dev-theme/index.php');
this.copy('footer.php', 'wp-content/themes/dev-theme/footer.php');
this.copy('functions.php', 'wp-content/themes/dev-theme/functions.php');
this.copy('header.php', 'wp-content/themes/dev-theme/header.php');
this.copy('404.php', 'wp-content/themes/dev-theme/404.php');
//
var context = {
site_name: this.appName
};
}
});
module.exports = WordpresscdGenerator;
create directories and _package.json like below
app/index.js
app/templates
app/templates/_package.json
app/templates/_gruntfile.js
Write like this.
{
"name": "appname",
"version": "0.0.0",
"dependencies": {
"grunt": "~0.4.6",
"grunt-contrib-connect": "~0.9.0",
"grunt-contrib-concat": "~0.5.1",
"grunt-contrib-cssmin": "~0.12.2",
"grunt-contrib-watch": "~0.6.1"
}
}
write _gruntfile.js
module.exports = function(grunt){
grunt.initConfig({
server: {
options: {
keepalive: true,
open: false,
middleware: function(){
var middleware = [];
middleware.push(function(req, res, next){
if (req.url !== '/') return next();
res.setHeader('Content-type', 'text/html');
var html = grunt.file.read('app/header.html');
html += grunt.file.read('app/footer.html');
res.end(html);
});
middleware.push(function(req, res, next){
if (req.url !== '/css/main.css') return next();
res.setHeader('Content-type', 'text/css');
var css = '';
var files = grunt.file.expand("app/css/*.css");
for (var i = 0; i < files.length; i++) {
css += grunt.file.read(files[i]);
}
res.end(css);
});
middleware.push(function(req, res, next){
res.statusCode = 404;
res.end('Not Found');
});
return middleware;
}
}
},
concat: {
dist: {
src: ['app/header.html', 'app/footer.html'],
dest: 'build/index.html'
}
},
cssmin: {
css: {
files: {
'build/css/main.css': ['app/css/*.css']
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.registerTask('serve', ['connect']);
grunt.registerTask('build', ['concat', 'cssmin']);
grunt.registerTask('default', ['build']); // 'default' = 'grunt'
};
Related
OK, so I am trying a new setup to give me a more efficient way of developing my sites.
At the moment I can only think of 3 stages, development, staging and build
As I'm using gulp, I have been typing gulp into Terminal to get started which then creates my build site.
Rather than run the Gulp command, I would like to use something like npm run development or npm run staging or npm run build
I understand by typing Gulp it automatically looks for the gulpfile.js file. How do I creat my own files?
I understand its something to do with scripts in the package.json file but I can't workout how.
Here's what I have so far:
{
"name": "Name",
"version": "1.0.0",
"description": "Description",
"main": "index.html",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"development": "node builds/development.js",
"staging": "node builds/staging.js",
"build": "node builds/build.js"
},
"author": "Author name here",
"license": "ISC",
"devDependencies": {
"gulp": "^4.0.2",
},
"dependencies": {
}
}
Now when I type 'npm run staging' (being a exact copy of gulpfile.js) I would expect it to start just like if I typed Gulp
UPDATE:
Here is my gulpfile
// --------------------------------------------
// Gulp Loader
// --------------------------------------------
// Stop having to put gulp. infront of the following
const {
src,
dest,
task,
watch,
series,
parallel
} = require("gulp");
// --------------------------------------------
// Dependencies
// --------------------------------------------
// HTML plugins
var htmlmin = require("gulp-htmlmin");
// CSS / SASS plugins
var sass = require('gulp-sass');
var cleanCSS = require('gulp-clean-css');
// Images plugins
// let imagemin = require("gulp-imagemin");
var embedSvg = require("gulp-embed-svg");
// Browser plugins
var browserSync = require('browser-sync').create();
// Utility plugins
var plumber = require("gulp-plumber");
var rename = require("gulp-rename");
var cache = require('gulp-cache');
var autoprefixer = require('gulp-autoprefixer');
var sourcemaps = require('gulp-sourcemaps');
var shell = require('shelljs');
var uglify = require('gulp-uglify');
var del = require("del");
var inject = require('gulp-inject');
var shell = require('shelljs');
var noop = require('gulp-noop');
// --------------------------------------------
// Get Home Folder location
// --------------------------------------------
//Displays Users/User
const homedir = require("os").homedir();
// Needed for next part
var path = require("path");
//Displays Users/User/Documents/Clients/clientname/Projects (This is where I create my client folders)
var pathDir = require("path").resolve(__dirname, "../../");
var pathSrc = require("path").resolve(__dirname, "../../../");
//Display the name of the Clients folder name
var parentFld = path
.dirname(pathDir)
.split(path.sep)
.pop();
var parentDir = path.basename(path.dirname(pathDir));
parentDir = parentFld.replace(/[^\w]/g, "");
parentDir = parentFld.replace(/[^\w]/g, "").toLowerCase();
// BrowserSync
function server(done) {
browserSync.init({
proxy: "http://" + parentDir + ".test",
host: parentDir + ".test",
open: "external",
notify: false
});
done();
}
// function watcher() {
// Serve files from the root of this project
// browserSync.init({
// proxy: "https://" + parentdir + ".test",
// // host: parentdir + ".test",
// open: "external",
// https: {
// key: homedir + "/.config/valet/Certificates/" + parentdir + ".test.key",
// cert: homedir + "/.config/valet/Certificates/" + parentdir + ".test.crt"
// },
// browser: "Google Chrome Canary",
// notify: false
// });
// --------------------------------------------
// Paths
// --------------------------------------------
var paths = {
htaccess: {
src: './source/.htaccess',
dest: './development/.htaccess',
},
html: {
src: './source/*.html',
prt: './source/partials/*.html',
dest: './development/'
},
styles: {
src: 'source/styles/*.css',
dest: 'development/styles/'
},
scripts: {
src: 'source/scripts/*.js',
dest: 'development/scripts'
}
}
// --------------------------------------------
// Tasks
// --------------------------------------------
//Basic task with a log - SHOW $homedir
function home(cb) {
console.log(fontBld);
cb()
}
task('default', function () {
console.log('Hello World!');
});
//Basic task with a log
function ssg(cb) {
console.log(parentDir);
cb()
}
// CONSOLE LOG
function console_log(cb) {
console.log(parentDir);
cb()
}
function valet_link(cb) {
shell.mkdir(['development']);
shell.cd(['./development']);
if (shell.exec('sudo valet link' + ' ' + parentDir).code !== 0) {
shell.echo('Error: Git commit failed');
shell.exit(1);
}
shell.cd(['..']);
cb()
}
// CLEAN
function clean(cb) {
del.sync(paths.html.dest, {
force: true
});
cb()
}
// HT ACCESS
function htaccess() {
return src(paths.htaccess.src)
.pipe(dest(paths.htaccess.dest));
}
// HTML
function html() {
var injectPartials = src(paths.html.prt, {
relative: true
});
var injectStyles = src([paths.styles.src], {
relative: true
});
var injectScripts = src(paths.scripts.src, {
relative: true
});
return src(paths.html.src)
.pipe(inject(injectPartials, {
starttag: '<!-- inject:header:{{ext}} -->',
transform: function (filePath, file) {
// return file contents as string
return file.contents.toString('utf8')
}
}))
.pipe(inject(injectStyles, {
addRootSlash: false,
ignorePath: '/source/'
}))
.pipe(inject(injectScripts, {
addRootSlash: false,
ignorePath: '/source/'
}))
.pipe(
embedSvg({
root: "./source/images/",
selectors: ".inline-svg"
})
)
.pipe(dest(paths.html.dest));
}
// CSS
function css() {
return src(paths.styles.src)
.pipe(sass({
outputStyle: 'compressed'
}))
.pipe(plumber())
.pipe(dest(paths.styles.dest))
}
// JS
function js() {
return src(paths.scripts.src)
.pipe(
rename({
basename: "main",
suffix: ".min"
})
)
.pipe(plumber())
.pipe(uglify())
.pipe(dest(paths.scripts.dest));
}
// IMAGES
function img(done) {
src(imageSrc + "*")
.pipe(imagemin())
.pipe(dest(imageDest));
done();
}
// FONTS
function fonts(done) {
src(fontSrc + "*").pipe(dest(fontDest));
done();
}
function clearCache(done) {
cache.clearAll();
done();
}
// --------------------------------------------
// Watch
// --------------------------------------------
function watcher() {
watch(paths.styles.src).on('change', series(css, browserSync.reload));
watch(paths.scripts.src).on('change', series(js, browserSync.reload));
watch(paths.htaccess.src).on('change', series(htaccess, browserSync.reload));
watch(paths.html.src).on('change', series(html, browserSync.reload));
}
// --------------------------------------------
// Compile
// --------------------------------------------
exports.test = series(clean, html)
exports.log = console_log
exports.valet = valet_link
// --------------------------------------------
// Build
// --------------------------------------------
// CONSOLE LOG
function build_log(cb) {
console.log("Please either use 'npm run production' or 'npm run development'");
cb()
}
var compile = series(clean, valet_link, series(html, css, js));
task('default', series(compile, parallel(server, watcher)));
You dont need to create multiple gulp files, you can simply have one gulp.js file and simply call your gulp file in you package.json the way you are already doing like so:
"scripts": {
"gulp": "gulp",
"test": "echo \"Error: no test specified\" && exit 1"
},
Than, on your gulp file you just create your exports like so:
exports.development = function devFunction(){ ... };
exports.staging = function stagingFunction(){ ... };
exports.build = function buildFunction(){ ... };
You would than run each task, you would call "gulp task" like so:
gulp development
I want to deploy my project local to production server.
At my local machine I am using gulp build gulp serve command.
This command is redirected to me at
http://localhost:3000.
When I added code on production server and run these command.
it is redirect to me at http://142.93.165.118:3000
I want to display original host url like:https://example.com
Currently it is displaying http://142.93.165.118:3000 on production server.
Here is my gulp.js code
'use strict';
/**
The custom gulp file to build and serve the web site.
*/
//The main gulp task creator
var gulp = require('gulp'),
connect = require('gulp-connect');
//SASS transpilation to CSS
var sass = require('gulp-sass');
//Refresh the browser when the files are updated.
var browserSync = require('browser-sync').create();
//Minify JS codes
var uglify = require('gulp-uglify');
//Filter files by extension and pass them to a callback
var gulpIf = require('gulp-if');
//Minify CSS codes
var cssnano = require('gulp-cssnano');
//CSS sourcemaps to find the class definistions easily
var sourcemaps = require('gulp-sourcemaps');
//Optimize images
var imagemin = require('gulp-imagemin');
//Caches the optimized images not to optimize them with every build/run
var cache = require('gulp-cache');
//Delete the given folder contents for clean up
var del = require('del');
//Run multiple tasks concurrently
var runSequence = require('run-sequence');
//Handles AngularJS dependency injection
var ngAnnotate = require('gulp-ng-annotate');
//Renames files
var rename = require('gulp-rename');
//Injects the JS and CSS file paths into the index.html file
var inject = require("gulp-inject");
//Concat(merge) files
var concat = require('gulp-concat');
//Reads bower files from bower.json to process them
var bowerMain = require('main-bower-files');
//Filter files by extension and return the paths.
var gulpFilter = require('gulp-filter');
//Minify HTML files
var htmlmin = require('gulp-htmlmin');
//Concatenates AngugularJS templates
var angularTemplatecache = require("gulp-angular-templatecache");
//This will redirect all requests to index.html file to allow seo friendly urls like tld/sports intead of tld/#/sports
var historyApiFallback = require('connect-history-api-fallback');
var minify = "yes";
var isServe = "false";
var conf = {
srcDir: 'src/',
appStylesDir: 'src/app/',
destDir: 'dist/',
cssDestDir: 'dist/css/',
imagesDestDir: 'dist/images/',
imagesSrcDir: 'src/images/',
fontsSrcDir: ['src/fonts/*', 'bower_components/bootstrap-sass/assets/fonts/bootstrap/*', 'bower_components/bootstrap/dist/fonts/*'],
fontsDestDir: 'dist/fonts/',
jsSrcDir: 'src/app/',
jsDestDir: 'dist/scripts/'
};
var bowerConf = {
"overrides": {
"admin-lte": {
"main": [
"**/AdminLTE.css",
"**/adminlte.js",
"**/_all-skins.min.css",
"**/jquery-jvectormap-1.2.2.min.js",
"**/jquery-jvectormap-world-mill-en.js",
"**/bootstrap3-wysihtml5.all.min.js",
"**/bootstrap3-wysihtml5.min.css",
"**/slider.css",
"**/bootstrap-timepicker.min.css",
"**/iCheck/**/_all.css",
"**/iCheck/**/futurico.css",
"**/iCheck/**/polaris.css",
"**/icheck.min.js",
"**/jquery.inputmask.js",
"**/jquery.inputmask.date.extensions.js",
"**/jquery.inputmask.extensions.js"
],
"dependencies": {
"jquery": "^3.2.1",
"jquery-ui": "1.11.4",
"jquery-slimscroll": "slimscroll#^1.3.8",
"jquery-sparkline": "^2.1.3",
"bootstrap": "^3.3.7",
"font-awesome": "^4.7.0",
"moment": "^2.18.1",
"chart.js": "1.0.*",
"datatables.net": "^1.10.15",
"datatables.net-bs": "^2.1.1",
"fastclick": "^1.0.6",
"Flot": "flot#^0.8.3",
"fullcalendar": "^3.4.0",
"ion.rangeSlider": "ionrangeslider#^2.2.0",
"jvectormap": "^1.2.2",
"jquery-knob": "^1.2.13",
"morris.js": "^0.5.1",
"PACE": "pace#^1.0.2",
"select2": "^4.0.3",
"Ionicons": "ionicons#^2.0.1",
"inputmask": "jquery.inputmask#^3.3.7",
"bootstrap-colorpicker": "^2.5.1",
"bootstrap-datepicker": "^1.7.0",
"bootstrap-daterangepicker": "^2.1.25",
"bootstrap-timepicker": "^0.5.2",
"bootstrap-slider": "*"
}
},
"bootstrap": {
"main": [
"**/bootstrap.min.css",
"**/bootstrap.min.js"
]
},
"mocha": {
"ignore": true
},
"jquery-slimscroll": {
"main": "**/jquery.slimscroll.min.js"
},
"inputmask": {
"ignore": true
},
"font-awesome": {
"main": [
"**/font-awesome.min.css",
"**/fontawesome-webfont.eot",
"**/fontawesome-webfont.woff2",
"**/fontawesome-webfont.woff",
"**/fontawesome-webfont.ttf",
"**/fontawesome-webfont.svg"
]
},
"Flot": {
"main": [
"**/jquery.flot.js",
"**/jquery.flot.resize.js",
"**/jquery.flot.pie.js",
"**/jquery.flot.categories.js"
]
},
"select2": {
"main": [
"**/select2.min.css",
"**/select2.full.min.js"
]
},
"bootstrap-colorpicker": {
"main": [
"**/bootstrap-colorpicker.min.css",
"**/bootstrap-colorpicker.min.js"
]
},
"ckeditor": {
"ignore": true
}
}
};
gulp.task('bower', function () {
var jsFilter = gulpFilter('**/*.js', {restore: true});
var cssFilter = gulpFilter(['**/*.css'], {restore: true});
var fontFilter = gulpFilter(['**/*.eot', '**/*.woff', '**/*.svg', '**/*.ttf'], {restore: true});
var imageFilter = gulpFilter(['**/*.gif', '**/*.png', '**/*.svg', '**/*.jpg', '**/*.jpeg'], {restore: true});
return gulp.src(bowerMain(bowerConf))
// JS
.pipe(jsFilter)
.pipe(concat('vendor.js'))
.pipe(gulp.dest(conf.jsDestDir))
.pipe(uglify())
.pipe(rename("vendor.min.js"))
.pipe(gulp.dest(conf.jsDestDir))
.pipe(jsFilter.restore)
// CSS
.pipe(cssFilter)
.pipe(concat('vendor.css'))
.pipe(cssnano())
.pipe(sourcemaps.write('.'))
.pipe(rename("vendor.min.css"))
.pipe(gulp.dest(conf.cssDestDir))
.pipe(cssFilter.restore)
// FONTS
.pipe(fontFilter)
.pipe(gulp.dest(conf.fontsDestDir))
.pipe(fontFilter.restore)
// IMAGES
.pipe(imageFilter)
.pipe(gulp.dest(conf.imagesDestDir))
.pipe(imageFilter.restore)
});
//JS operations
gulp.task('js', function () {
return gulp.src([
conf.jsSrcDir + '/app.js',
conf.jsSrcDir + '/core/**/*.js',
conf.jsSrcDir + '/pages/**/*.js',
conf.jsSrcDir + '/modules/**/*.js',
conf.jsSrcDir + '**/*.html'
])
.pipe(gulpIf('*.html', htmlmin({
removeEmptyAttributes: true,
removeAttributeQuotes: true,
collapseBooleanAttributes: true,
collapseWhitespace: true
})))
.pipe(gulpIf('*.html', angularTemplatecache('templateCacheHtml.js', {
module: 'adminlte',
root: 'app'
})))
.pipe(concat("app.js"))
.pipe(ngAnnotate())
//.pipe(gulpIf(minify === 'yes', uglify()))
.pipe(rename("app.min.js"))
.pipe(gulp.dest(conf.jsDestDir))
});
//SASS operations
gulp.task('sass', function () {
return gulp.src(
[
conf.srcDir + "index.scss",
conf.appStylesDir + '**/**/*.scss'
])
.pipe(concat("app.css"))
.pipe(sass().on('error', sass.logError)) // log errors to console
.pipe(gulpIf(minify === 'yes', cssnano())) //Minify
.pipe(rename('app.min.css'))
.pipe(gulp.dest(conf.cssDestDir)) // Save in the given folder
});
//INJECT operations
gulp.task('inject', function () {
return gulp.src('src/index.html')
//Remove dist from the link of the css and js files.
.pipe(inject(gulp.src(conf.cssDestDir + 'vendor.min.css', {read: false}), {
ignorePath: 'dist/',
starttag: '<!-- bower:css -->',
endtag: '<!-- endbower:css -->'
}))
.pipe(inject(gulp.src(conf.cssDestDir + 'app.min.css', {read: false}), {
ignorePath: 'dist/',
starttag: '<!-- app:css -->',
endtag: '<!-- endapp:css -->'
}))
.pipe(inject(gulp.src(conf.jsDestDir + (isServe === "yes" ? 'vendor.js' : 'vendor.min.js'), {read: false}), {
ignorePath: 'dist/',
starttag: '<!-- bower:js -->',
endtag: '<!-- endbower:js -->'
}))
.pipe(inject(gulp.src(conf.jsDestDir + 'app.min.js', {read: false}), {
ignorePath: 'dist/',
starttag: '<!-- app:js -->',
endtag: '<!-- endapp:js -->'
}))
.pipe(gulp.dest(conf.destDir));
});
// Watchers
gulp.task('watch', function () {
gulp.watch('src/app/**/*.scss', ['sass', browserSync.reload]);
gulp.watch('src/app/**/*.html', ['js', browserSync.reload]);
gulp.watch('src/app/**/*.js', ['js', browserSync.reload]);
});
// Start browserSync server
gulp.task('browserSync', function () {
browserSync.init({
server: {
baseDir: 'dist',
livereload: true,
index: 'index.html',
middleware: [historyApiFallback()]
}
});
});
gulp.task('images', function () {
return gulp.src(conf.imagesSrcDir + '**/*.+(png|jpg|jpeg|gif|svg|ico)')
// Caching images
.pipe(cache(imagemin({
interlaced: true
})))
.pipe(gulp.dest(conf.imagesDestDir))
});
//Copy fonts
gulp.task('fonts', function () {
return gulp.src(conf.fontsSrcDir)
.pipe(gulp.dest(conf.fontsDestDir))
});
//Clean up
gulp.task('clean', function () {
return del.sync('dist').then(function (cb) {
return cache.clearAll(cb);
});
});
gulp.task('clear', () =>
cache.clearAll()
);
gulp.task('clean:dist', function () {
console.log("clean dist should backup the current dist folder when build called");
return del.sync(['dist/**/*', '!dist/images', '!dist/images/**/*']);
});
gulp.task('serve', function (callback) {
minify = "no";
isServe = "yes";
runSequence(
['sass', 'js'],
['inject'],
['watch', 'browserSync'],
callback
)
});
gulp.task('connect', function() {
connect.server({
root: 'app',
livereload: true
});
});
gulp.task('default', ['connect']);
var onError = function (err) {
console.log(err);
};
var gulp = require('gulp');
var webserver = require('gulp-webserver');
gulp.task('build', function (callback) {
runSequence(
'clean:dist',
'sass',
'js',
'bower',
['images', 'fonts'],
['inject'],
callback
)
});
Could you provide me proper way.
step 1) I have moved all files of dist folder to root directory.
step 2) Deleted dist folder
step 3) run index.html
its working for me
I have implementing gulp task in the project.
I have installed gulp-assests-version-replace to make version control file of css file.
Now I want to run above task after creating the app.css. It runs before creating the app.css, so version control file cannot be created.
Below is the gulp-file for running the gulp tasks.
var gulp = require('gulp');
var autoprefixer = require('gulp-autoprefixer');
var changed = require('gulp-changed');
var concat = require('gulp-concat');
var del = require('del');
var gulpif = require('gulp-if');
var gutil = require('gulp-util');
var imagemin = require('gulp-imagemin');
var jshint = require('gulp-jshint');
var notify = require('gulp-notify');
var plumber = require('gulp-plumber');
var rename = require('gulp-rename');
var sass = require('gulp-sass');
var assetsVersionReplace = require('gulp-assets-version-replace');
var uglify = require('gulp-uglify');
var path = {
assets: 'skin/frontend/custom_theme/default/'
};
var config = {
tasks: {
css: {
autoprefixerOptions: {
// For "browserslist" see "package.json"
cascade: false,
supports: false // See: https://github.com/filamentgroup/select-css/issues/17
},
dest: path.assets + 'css/build',
sassOptions: {
outputStyle: 'compressed'
},
src: path.assets + 'css/src/**/*.scss'
},
version: {
autoprefixerOptions: {
// For "browserslist" see "package.json"
cascade: false,
supports: false // See: https://github.com/filamentgroup/select-css/issues/17
},
dest: path.assets + 'css/build',
sassOptions: {
outputStyle: 'compressed'
},
src: path.assets + 'css/build/app.css'
}
}
}
gulp.task('default', ['clean'], function () {
gulp.start('css');
gulp.start('assetsVersionReplace');
});
gulp.task('clean', function () {
return del([
path.assets + 'css/build',
path.assets + 'js/build',
path.assets + 'js/min',
path.assets + 'img/build'
]);
});
gulp.task('css', function () {
return gulp.src(config.tasks.css.src)
.pipe(plumber({
errorHandler: reportError
}))
.pipe(sass(config.tasks.css.sassOptions))
.pipe(autoprefixer(config.tasks.css.autoprefixerOptions))
.pipe(gulp.dest(config.tasks.css.dest));
});
gulp.task('assetsVersionReplace', function () {
return gulp.src(config.tasks.version.src)
.pipe(assetsVersionReplace({
replaceTemplateList: [
'app/design/frotend/custom_theme/default/template/page/head.phtml'
]
}))
.pipe(gulp.dest(config.tasks.version.dest))
});
gulp.task('watch', function () {
// Run "default" immediately
gulp.start('default');
// CSS
gulp.watch(config.tasks.css.src, ['css']);
gulp.watch(config.tasks.version.src, ['assetsVersionReplace']);
});
How can I run assetsVersionReplace task after creating the css (or after runnung 'CSS' task)?
Either change
gulp.task('assetsVersionReplace', function () {
to
gulp.task('assetsVersionReplace', ['css'], function () {
or, if that isn't an option, add a helper task
gulp.task('assetsVersionReplaceAfterCss', ['css'], function () {
gulp.start('assetsVersionReplace');
}
and use that instead
Why don't you use gulp series.
gulp.task('default',
gulp.series(
'css',
'assetsVersionReplace'
)
);
It seems that example-template.dust somehow gets cached. The first time running the gulp default task it correctly takes the current version of example-template.dust and renders it correctly in index.html.
But later changes to example-template.dust aren't included in the rendered index.html even though the watch task correctly fires and executes the dust task.
I'm thinking it has to do with some configuration errors.
Here is the gulp tasks and templates. Everything else works.
example-template.dust
Hello, from a template. Rendered with <b>{type}</b>
index.html
<!DOCTYPE html>
<html>
<head>
<title>{name}</title>
<link rel="stylesheet" href="main.css"/>
</head>
<body>
<h1>version \{version}</h1>
<p>
{>example-template type="gulp"/}<br/>
There are special escape tags that you can use to escape a raw { or } in dust.<br/>
{~lb}hello{~rb}
</p>
<script src="main.js"></script>
</body>
</html>
gulp-dust-html task
var gulp = require('gulp');
var dust = require('dustjs-linkedin');
var browserSync = require('browser-sync');
var error = require('./errorHandling.js');
var dusthtml = require('gulp-dust-html');
var config = require('../../config.js');
gulp.task('dust', function () {
return gulp.src(config.build.src+'/**/*.html')
.pipe(dusthtml({
basePath: config.build.src+'/',
data: config.build.data
}))
.on('error', error)
.pipe(gulp.dest(config.build.dev+'/'))
.pipe(browserSync.reload({stream:true}));
});
gulp.task('watch-dust', ['dust'], browserSync.reload);
watch task
var gulp = require('gulp');
var watch = require('gulp-watch');
var reload = require('browser-sync').reload;
var config = require('../../config.js');
gulp.task('watch', function() {
gulp.watch(config.build.src+"/**/*.scss", ['sass', reload]);
gulp.watch(config.build.images, ['images', reload]);
gulp.watch([config.build.src+"/**/*.dust"], ['watch-dust', reload]);
gulp.watch([config.build.src+"/**/*.html"], ['watch-dust', reload]);
});
default gulp task
gulp.task('default', ['browserSync','images', 'iconFont', 'sass', 'js', 'dust', 'watch']);
I'm open for alternative suggestions as well.
Atm I'm thinking it could be an idea to use https://www.npmjs.com/package/gulp-shell and link it to the watch task.
ps: I don't have enough reputation to create a gulp-dust-html tag
As #Interrobang said, dust.config.cache = false solved it.
Here is the updated gulp-dust-html module (not on npm)
'use strict';
var gutil = require('gulp-util');
var path = require('path');
var fs = require('fs');
var through = require('through2');
var dust = require('dustjs-linkedin');
module.exports = function (options) {
if (!options)
options = {}
var basePath = options.basePath || '.';
var data = options.data || {};
var defaultExt = options.defaultExt || '.dust';
var whitespace = options.whitespace || false;
dust.config.cache = options.cache || false; //default cache disabling of templates.
dust.onLoad = function(filePath, callback) {
if(!path.extname(filePath).length)
filePath += defaultExt;
if(filePath.charAt(0) !== "/")
filePath = basePath + "/" + filePath;
fs.readFile(filePath, "utf8", function(err, html) {
if(err) {
console.error("Template " + err.path + " does not exist");
return callback(err);
}
try {
callback(null, html);
} catch(err) {
console.error("Error parsing file", err);
}
});
};
if (whitespace)
dust.optimizers.format = function (ctx, node) { return node; };
return through.obj(function (file, enc, cb) {
if (file.isNull()) {
this.push(file);
return cb();
}
if (file.isStream()) {
this.emit('error', new gutil.PluginError('gulp-dust', 'Streaming not supported'));
return cb();
}
try {
var contextData = typeof data === 'function' ? data(file) : data;
var finalName = typeof name === 'function' && name(file) || file.relative;
var tmpl = dust.compileFn(file.contents.toString(), finalName);
var that = this;
tmpl(contextData, function(err, out){
if (err){
that.emit('error', new gutil.PluginError('gulp-dust', err));
return;
}
file.contents = new Buffer(out);
file.path = gutil.replaceExtension(file.path, '.html');
that.push(file);
cb();
})
} catch (err) {
this.emit('error', new gutil.PluginError('gulp-dust', err));
}
});
};
I'm trying to use gulp-data with gulp-jade in my workflow but I'm getting an error related to the gulp-data plugin.
Here is my gulpfile.js
var gulp = require('gulp'),
plumber = require('gulp-plumber'),
browserSync = require('browser-sync'),
jade = require('gulp-jade'),
data = require('gulp-data'),
path = require('path'),
sass = require('gulp-ruby-sass'),
prefix = require('gulp-autoprefixer'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
process = require('child_process');
gulp.task('default', ['browser-sync', 'watch']);
// Watch task
gulp.task('watch', function() {
gulp.watch('*.jade', ['jade']);
gulp.watch('public/css/**/*.scss', ['sass']);
gulp.watch('public/js/*.js', ['js']);
});
var getJsonData = function(file, cb) {
var jsonPath = './data/' + path.basename(file.path) + '.json';
cb(require(jsonPath))
};
// Jade task
gulp.task('jade', function() {
return gulp.src('*.jade')
.pipe(plumber())
.pipe(data(getJsonData))
.pipe(jade({
pretty: true
}))
.pipe(gulp.dest('Build/'))
.pipe(browserSync.reload({stream:true}));
});
...
// Browser-sync task
gulp.task('browser-sync', ['jade', 'sass', 'js'], function() {
return browserSync.init(null, {
server: {
baseDir: 'Build'
}
});
});
And this is a basic json file, named index.jade.json
{
"title": "This is my website"
}
The error I get is:
Error in plugin 'gulp-data'
[object Object]
You are getting error because in getJsonData you pass required data as first argument to the callback. That is reserved for possible errors.
In your case the callback isn't needed. Looking at gulp-data usage example this should work:
.pipe(data(function(file) {
return require('./data/' + path.basename(file.path) + '.json');
}))
Full example:
var gulp = require('gulp');
var jade = require('gulp-jade');
var data = require('gulp-data');
var path = require('path');
var fs = require('fs');
gulp.task('jade', function() {
return gulp.src('*.jade')
.pipe(data(function(file) {
return require('./data/' + path.basename(file.path) + '.json');
}))
.pipe(jade({ pretty: true }))
.pipe(gulp.dest('build/'));
});
Use this if you're running the task on gulp.watch:
.pipe(data(function(file) {
return JSON.parse(fs.readFileSync('./data/' + path.basename(file.path) + '.json'));
}))