I'm running my own Ubuntu 16.04.1 droplet and have just installed 'nodejs', npm, and bower globally. Then installed npm and bower on the Sage theme I've been working with. I'm able to gulp almost everything but once I get to images, I'm thrown with an error I've been having trouble diagnosing. Any help is always much appreciated!
root#myserver-ubuntu:/var/www/html/mydomain.com/public_html/bedrock/web/app/themes/mytheme# gulp images
[00:46:45] Using gulpfile /var/www/html/mydomain.com/public_html/bedrock/web/app/themes/mytheme/gulpfile.js
[00:46:45] Starting 'images'...
events.js:141
throw er; // Unhandled 'error' event
^
Error: Command failed: /var/www/html/mydomain.com/public_html/bedrock/web/app/themes/mytheme/node_modules/optipng-bin/vendor/optipng -strip all -clobber -force -fix -o 2 -out /tmp/2fd7e3c1-977c-4ac4-9886-a84ecd44e9e8 /tmp/49ebf02e-f383-46e2-bc40-d6b03b441380
/var/www/html/mydomain.com/public_html/bedrock/web/app/themes/mytheme/node_modules/optipng-bin/vendor/optipng: 1: /var/www/html/mydomain.com/public_html/bedrock/web/app/themes/mytheme/node_modules/optipng-bin/vendor/optipng: Syntax error: "(" unexpected
at ChildProcess.exithandler (child_process.js:213:12)
at emitTwo (events.js:87:13)
at ChildProcess.emit (events.js:172:7)
at maybeClose (internal/child_process.js:821:16)
at Socket.<anonymous> (internal/child_process.js:319:11)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at Pipe._onclose (net.js:469:12)
This is the gulpfile.js -
// ## Globals
var argv = require('minimist')(process.argv.slice(2));
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync').create();
var changed = require('gulp-changed');
var concat = require('gulp-concat');
var flatten = require('gulp-flatten');
var gulp = require('gulp');
var gulpif = require('gulp-if');
var imagemin = require('gulp-imagemin');
var jshint = require('gulp-jshint');
var lazypipe = require('lazypipe');
var less = require('gulp-less');
var merge = require('merge-stream');
var cssNano = require('gulp-cssnano');
var plumber = require('gulp-plumber');
var rev = require('gulp-rev');
var runSequence = require('run-sequence');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
// See https://github.com/austinpray/asset-builder
var manifest = require('asset-builder')('./assets/manifest.json');
// `path` - Paths to base asset directories. With trailing slashes.
// - `path.source` - Path to the source files. Default: `assets/`
// - `path.dist` - Path to the build directory. Default: `dist/`
var path = manifest.paths;
// `config` - Store arbitrary configuration values here.
var config = manifest.config || {};
// `globs` - These ultimately end up in their respective `gulp.src`.
// - `globs.js` - Array of asset-builder JS dependency objects. Example:
// ```
// {type: 'js', name: 'main.js', globs: []}
// ```
// - `globs.css` - Array of asset-builder CSS dependency objects. Example:
// ```
// {type: 'css', name: 'main.css', globs: []}
// ```
// - `globs.fonts` - Array of font path globs.
// - `globs.images` - Array of image path globs.
// - `globs.bower` - Array of all the main Bower files.
var globs = manifest.globs;
// `project` - paths to first-party assets.
// - `project.js` - Array of first-party JS assets.
// - `project.css` - Array of first-party CSS assets.
var project = manifest.getProjectGlobs();
// CLI options
var enabled = {
// Enable static asset revisioning when `--production`
rev: argv.production,
// Disable source maps when `--production`
maps: !argv.production,
// Fail styles task on error when `--production`
failStyleTask: argv.production,
// Fail due to JSHint warnings only when `--production`
failJSHint: argv.production,
// Strip debug statments from javascript when `--production`
stripJSDebug: argv.production
};
// Path to the compiled assets manifest in the dist directory
var revManifest = path.dist + 'assets.json';
// ## Reusable Pipelines
// See https://github.com/OverZealous/lazypipe
// ### CSS processing pipeline
// Example
// ```
// gulp.src(cssFiles)
// .pipe(cssTasks('main.css')
// .pipe(gulp.dest(path.dist + 'styles'))
// ```
var cssTasks = function(filename) {
return lazypipe()
.pipe(function() {
return gulpif(!enabled.failStyleTask, plumber());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.init());
})
.pipe(function() {
return gulpif('*.less', less());
})
.pipe(function() {
return gulpif('*.scss', sass({
outputStyle: 'nested', // libsass doesn't support expanded yet
precision: 10,
includePaths: ['.'],
errLogToConsole: !enabled.failStyleTask
}));
})
.pipe(concat, filename)
.pipe(autoprefixer, {
browsers: [
'last 2 versions',
'android 4',
'opera 12'
]
})
.pipe(cssNano, {
safe: true
})
.pipe(function() {
return gulpif(enabled.rev, rev());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.write('.', {
sourceRoot: 'assets/styles/'
}));
})();
};
// ### JS processing pipeline
// Example
// ```
// gulp.src(jsFiles)
// .pipe(jsTasks('main.js')
// .pipe(gulp.dest(path.dist + 'scripts'))
// ```
var jsTasks = function(filename) {
return lazypipe()
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.init());
})
.pipe(concat, filename)
.pipe(uglify, {
compress: {
'drop_debugger': enabled.stripJSDebug
}
})
.pipe(function() {
return gulpif(enabled.rev, rev());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.write('.', {
sourceRoot: 'assets/scripts/'
}));
})();
};
// ### Write to rev manifest
// If there are any revved files then write them to the rev manifest.
// See https://github.com/sindresorhus/gulp-rev
var writeToManifest = function(directory) {
return lazypipe()
.pipe(gulp.dest, path.dist + directory)
.pipe(browserSync.stream, {match: '**/*.{js,css}'})
.pipe(rev.manifest, revManifest, {
base: path.dist,
merge: true
})
.pipe(gulp.dest, path.dist)();
};
// ## Gulp tasks
// Run `gulp -T` for a task summary
// ### Styles
// `gulp styles` - Compiles, combines, and optimizes Bower CSS and project CSS.
// By default this task will only log a warning if a precompiler error is
// raised. If the `--production` flag is set: this task will fail outright.
gulp.task('styles', ['wiredep'], function() {
var merged = merge();
manifest.forEachDependency('css', function(dep) {
var cssTasksInstance = cssTasks(dep.name);
if (!enabled.failStyleTask) {
cssTasksInstance.on('error', function(err) {
console.error(err.message);
this.emit('end');
});
}
merged.add(gulp.src(dep.globs, {base: 'styles'})
.pipe(cssTasksInstance));
});
return merged
.pipe(writeToManifest('styles'));
});
// ### Scripts
// `gulp scripts` - Runs JSHint then compiles, combines, and optimizes Bower JS
// and project JS.
gulp.task('scripts', ['jshint'], function() {
var merged = merge();
manifest.forEachDependency('js', function(dep) {
merged.add(
gulp.src(dep.globs, {base: 'scripts'})
.pipe(jsTasks(dep.name))
);
});
return merged
.pipe(writeToManifest('scripts'));
});
// ### Fonts
// `gulp fonts` - Grabs all the fonts and outputs them in a flattened directory
// structure. See: https://github.com/armed/gulp-flatten
gulp.task('fonts', function() {
return gulp.src(globs.fonts)
.pipe(flatten())
.pipe(gulp.dest(path.dist + 'fonts'))
.pipe(browserSync.stream());
});
// ### Images
// `gulp images` - Run lossless compression on all the images.
gulp.task('images', function() {
return gulp.src(globs.images)
.pipe(imagemin({
progressive: true,
interlaced: true,
svgoPlugins: [{removeUnknownsAndDefaults: false}, {cleanupIDs: false}]
}))
.pipe(gulp.dest(path.dist + 'images'))
.pipe(browserSync.stream());
});
// ### JSHint
// `gulp jshint` - Lints configuration JSON and project JS.
gulp.task('jshint', function() {
return gulp.src([
'bower.json', 'gulpfile.js'
].concat(project.js))
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'))
.pipe(gulpif(enabled.failJSHint, jshint.reporter('fail')));
});
// ### Clean
// `gulp clean` - Deletes the build folder entirely.
gulp.task('clean', require('del').bind(null, [path.dist]));
// ### Watch
// `gulp watch` - Use BrowserSync to proxy your dev server and synchronize code
// changes across devices. Specify the hostname of your dev server at
// `manifest.config.devUrl`. When a modification is made to an asset, run the
// build step for that asset and inject the changes into the page.
// See: http://www.browsersync.io
gulp.task('watch', function() {
browserSync.init({
files: ['{lib,templates}/**/*.php', '*.php'],
proxy: config.devUrl,
snippetOptions: {
whitelist: ['/wp-admin/admin-ajax.php'],
blacklist: ['/wp-admin/**']
}
});
gulp.watch([path.source + 'styles/**/*'], ['styles']);
gulp.watch([path.source + 'scripts/**/*'], ['jshint', 'scripts']);
gulp.watch([path.source + 'fonts/**/*'], ['fonts']);
gulp.watch([path.source + 'images/**/*'], ['images']);
gulp.watch(['bower.json', 'assets/manifest.json'], ['build']);
});
// ### Build
// `gulp build` - Run all the build tasks but don't clean up beforehand.
// Generally you should be running `gulp` instead of `gulp build`.
gulp.task('build', function(callback) {
runSequence('styles',
'scripts',
['fonts', 'images'],
callback);
});
// ### Wiredep
// `gulp wiredep` - Automatically inject Less and Sass Bower dependencies. See
// https://github.com/taptapship/wiredep
gulp.task('wiredep', function() {
var wiredep = require('wiredep').stream;
return gulp.src(project.css)
.pipe(wiredep())
.pipe(changed(path.source + 'styles', {
hasChanged: changed.compareSha1Digest
}))
.pipe(gulp.dest(path.source + 'styles'));
});
// ### Gulp
// `gulp` - Run a complete build. To compile for production run `gulp --production`.
gulp.task('default', ['clean'], function() {
gulp.start('build');
});
I will update this for anybody that may fall here in the future.
I couldn't locate the exact reason why gulp failed, my guess is that it's a spacing/tab bug. I deleted node_modules from the sage theme and reran npm install, and the error corrected itself.
Related
I am trying building a website with a clone from https://github.com/cssninjaStudio/krypton.
I can run the project locally with yarn run dev command working properly, but when i try to build the app to host in a VPS with yarn build or yarn run prod giving an error
Task never defined: prod
Here is my gulp.js
const del = require('del');
const options = require("./config");
const browserSync = require('browser-sync').create();
const sass = require('gulp-sass');
const bourbon = require('node-bourbon').includePaths;
const postcss = require('gulp-postcss');
const concat = require('gulp-concat');
const uglify = require('gulp-uglify');
const imagemin = require('gulp-imagemin');
const cleanCSS = require('gulp-clean-css');
const purgecss = require('gulp-purgecss');
const sourcemaps = require('gulp-sourcemaps');
const autoprefixer = require('gulp-autoprefixer');
const panini = require('panini');
const browserify = require("browserify");
const babelify = require("babelify");
const source = require("vinyl-source-stream");
const nodepath = 'node_modules/';
sass.compiler = require('sass');
//Note : Webp still not supported in major browsers including forefox
//const webp = require('gulp-webp'); //For converting images to WebP format
//const replace = require('gulp-replace'); //For Replacing img formats to webp in html
const logSymbols = require('log-symbols'); //For Symbolic Console logs :) :P
//Load Previews on Browser on dev
function livePreview(done) {
browserSync.init({
server: {
baseDir: options.paths.dist.base
},
port: options.config.port || 5000
});
done();
}
//Copy latest installed Bulma
function setupBulma() {
console.log("\n\t" + logSymbols.info, "Installing Bulma Files..\n");
return src([nodepath + 'bulma/*.sass', nodepath + 'bulma/**/*.sass'])
.pipe(dest('src/sass/'));
}
//Compile Sass code
function compileSASS() {
console.log("\n\t" + logSymbols.info, "Compiling Bulma Sass..\n");
return src(['src/sass/bulma.sass'])
.pipe(sass({
outputStyle: 'compressed',
sourceComments: 'map',
sourceMap: 'sass',
includePaths: bourbon
}).on('error', sass.logError))
.pipe(autoprefixer('last 2 versions'))
.pipe(dest('dist/assets/css'))
.pipe(browserSync.stream());
}
//Compile Scss code
function compileSCSS() {
console.log("\n\t" + logSymbols.info, "Compiling App SCSS..\n");
return src(['src/scss/main.scss'])
.pipe(sass({
outputStyle: 'compressed',
sourceComments: 'map',
sourceMap: 'scss',
includePaths: bourbon
}).on('error', sass.logError))
.pipe(autoprefixer('last 2 versions'))
.pipe(dest('dist/css'))
.pipe(browserSync.stream());
}
//Compile HTML partials with Panini
function compileHTML() {
console.log("\n\t" + logSymbols.info, "Compiling HTML..\n");
panini.refresh();
return src('src/pages/**/*.html')
.pipe(panini({
root: 'src/pages/',
layouts: 'src/layouts/',
partials: 'src/partials/',
helpers: 'src/helpers/',
data: 'src/data/'
}))
.pipe(dest('dist'))
.pipe(browserSync.stream());
}
//Concat CSS Plugins
function concatCssPlugins() {
console.log("\n\t" + logSymbols.info, "Compiling Plugin styles..\n");
return src([
nodepath + 'simplebar/dist/simplebar.min.css',
nodepath + 'plyr/dist/plyr.css',
nodepath + 'codemirror/lib/codemirror.css',
nodepath + 'codemirror/theme/shadowfox.css',
'src/vendor/css/*',
])
.pipe(sourcemaps.init())
.pipe(concat('app.css'))
.pipe(sourcemaps.write('./'))
.pipe(dest('dist/css'))
.pipe(browserSync.stream());
}
//Reset Panini Cache
function resetPages(done) {
console.log("\n\t" + logSymbols.info, "Clearing Panini Cache..\n");
panini.refresh();
done();
}
//Triggers Browser reload
function previewReload(done) {
console.log("\n\t" + logSymbols.info, "Reloading Browser Preview.\n");
browserSync.reload();
done();
}
//Development Tasks
function devHTML() {
return src(`${options.paths.src.base}/**/*.html`).pipe(dest(options.paths.dist.base));
}
//Optimize images
function devImages() {
return src(`${options.paths.src.img}/**/*`).pipe(dest(options.paths.dist.img));
}
// Let's write our task in a function to keep things clean
function javascriptBuild() {
// Start by calling browserify with our entry pointing to our main javascript file
return (
browserify({
entries: [`${options.paths.src.js}/main.js`],
// Pass babelify as a transform and set its preset to #babel/preset-env
transform: [babelify.configure({ presets: ["#babel/preset-env"] })]
})
// Bundle it all up!
.bundle()
// Source the bundle
.pipe(source("bundle.js"))
// Then write the resulting files to a folder
.pipe(dest(`dist/js`))
);
}
function copyFonts() {
console.log("\n\t" + logSymbols.info, "Copying fonts to dist folder.\n");
return src([
'src/fonts/*',
])
.pipe(dest('dist/fonts'))
.pipe(browserSync.stream());
}
//Copy data files
function copyData() {
console.log("\n\t" + logSymbols.info, "Copying data files..\n");
return src([
'src/data/**/*',
])
.pipe(dest('dist/data'))
.pipe(browserSync.stream());
}
function watchFiles() {
//watch('src/**/*.html', compileHTML);
watch(`${options.paths.src.base}/**/*.html`, series(compileHTML, previewReload));
watch(['src/scss/**/*', 'src/scss/*'], compileSCSS);
watch(`${options.paths.src.js}/**/*.js`, series(javascriptBuild, previewReload));
watch(`${options.paths.src.img}/**/*`, series(devImages, previewReload));
console.log("\n\t" + logSymbols.info, "Watching for Changes..\n");
}
function devClean() {
console.log("\n\t" + logSymbols.info, "Cleaning dist folder for fresh start.\n");
return del([options.paths.dist.base]);
}
exports.setup = series(setupBulma);
exports.default = series(
devClean, // Clean Dist Folder
resetPages,
parallel(copyFonts, concatCssPlugins, compileSCSS, javascriptBuild, devImages, compileHTML),
livePreview, // Live Preview Build
watchFiles // Watch for Live Changes
);
Need some help to build this website and host it in VPS
Many Thanks in Advance
The prod task is not define within the Gulp file. The dev task is, because it is calling the default gulp task (gulp with no arg is calling the default which is found at the end of the gulp file
exports.default = series(
devClean, // Clean Dist Folder
resetPages,
parallel(copyFonts, concatCssPlugins, compileSCSS, javascriptBuild, devImages, compileHTML),
livePreview, // Live Preview Build
watchFiles // Watch for Live Changes
);
Take a look at your package.json file, this is were the script name are define (such as dev and prod.)
"scripts": {
"dev": "gulp",
"build": "gulp prod",
"prod": "gulp prod",
"preinstall": "npx npm-force-resolutions"
},
So you should create a prod method in your gulp.js and should only call usefull method for prod env (remove livePreview and watch, you are most likely only build and deploy.)
I prefer to task definition like this,
gulp.task("prod", function (callback) {
config.runCleanBuilds = true;
return runSequence(
"taskA",
"taskB",
"taskC",
callback);
});
but you could do it the same way they do in their gulp file I guess
exports.prod = series(
devClean, // Clean Dist Folder
resetPages,
parallel(copyFonts, concatCssPlugins, compileSCSS, javascriptBuild, devImages, compileHTML)
);
I upgraded the gulp to 4.0.2 from Gulp version 3. it will not detect changes when the tracked JSa and SCSS file is changed.
Gulp version I am using :-
CLI version: 2.3.0
Local version: 4.0.2
gulpfile.js
'use strict';
var gulp = require('gulp'),
sass = require('gulp-sass'),
del = require('del'),
jshint = require('gulp-jshint'),
concat = require('gulp-concat'),
rename = require('gulp-rename'),
uglify = require('gulp-uglify'),
strip = require('gulp-strip-comments'),
livereload = require('gulp-livereload'),
http = require('http'),
st = require('st'),
sourcemaps = require('gulp-sourcemaps'),
ngAnnotate = require('gulp-ng-annotate'),
babel = require('gulp-babel'),
uglifycss = require('gulp-uglifycss'),
browserSync = require('browser-sync').create();
//Rerun the task when a file changes
var watch_hintJs = ['./global/util/*.js', './global/util/**/*.js', './modules/**/*Service.js', './modules/**/*Directive.js', './modules/**/*Controller.js', './modules/**/*Constant.js'];
var watch_hintscss = ['./global/scss/*.scss', './modules/**/*.scss'];
// This method is used to delete the files
gulp.task('clean', ()=> {
return del(['./assets/css']);
});
var globalCSS = ['./assets/libs/css/**','./assets/libs/css/*.css'];
gulp.task('css', ()=> {
return gulp.src(globalCSS)
.pipe(concat('myapp-main-libs.css'))
.pipe(uglifycss({
"uglyComments": true
}))
.pipe(gulp.dest('./assets/css/'));
});
/* SASS TO CSS CONVERSION*/
gulp.task('sass', ()=> {
return gulp.src(['./global/scss/*.scss', './global/scss/lib/*.scss', './modules/**/*.scss'])
.pipe(sass().on('error', sass.logError))
.pipe(sass())
.pipe(concat('myapp-main.css'))
//.pipe(strip())
.pipe(uglifycss({
"uglyComments": true
}))
.pipe(gulp.dest('./assets/css/'));
});
//This method is converting all JS files to Single file//
var jsFiles = ['./global/util/*.js', './global/util/lib/*.js', './global/util/components/*.js',
'./modules/**/*Service.js', './modules/**/*Directive.js', './modules/**/*Controller.js', './modules/**/*Constant.js'],
jsDest = './assets/js/',
jsLibs = [
'assets/libs/js/tether.min.js',
'assets/libs/js/jquery.min.js',
'assets/libs/js/jquery-ui-min.js',
'assets/libs/js/bootstrap.min.js',
'assets/libs/js/angular.min.js',
'assets/libs/js/angular-ui-router.min.js',
'assets/libs/js/ui-grid-min.js',
'assets/libs/js/html2canvas.js',
'assets/libs/js/ui-bootstrap-tpls-2.5.0.min.js',
'assets/libs/js/accordian.js',
'assets/libs/js/angularResizable.js',
'assets/libs/js/angular-animate.min.js',
'assets/libs/js/ngToast.js',
'assets/libs/js/angular-sanitize.js',
'assets/libs/js/pubsub.js',
'assets/libs/js/angular-environment.js',
'assets/libs/js/deferred-with-update.js',
'assets/libs/js/multiselect.js',
'assets/libs/js/angular-chart.min.js',
'assets/libs/js/common.js',
'assets/libs/js/bootstrap-colorpicker-module.min.js',
'assets/libs/js/dom-to-image.js',
'assets/libs/js/alasql.min.js',
'assets/libs/js/xlsx.core.min.js',
'node_modules/babel-polyfill/dist/polyfill.min.js',
'assets/libs/js/jquery.csv.js',
'assets/libs/js/z-worker.js',
'assets/libs/js/zip.js'
];
gulp.task('libs', ()=> {
return gulp.src(jsLibs)
.pipe(strip())
.pipe(concat('myapp-lib-scripts.js'))
.pipe(gulp.dest(jsDest));
});
var minify = require('gulp-minify');
gulp.task('scripts', ()=> {
return gulp.src(jsFiles)
.pipe(jshint())
.pipe(sourcemaps.init())
.pipe(babel({
presets: ['es2015', 'stage-3'],
"plugins": ["transform-async-to-generator"]
}))
.pipe(concat('myapp-scripts.js'))
.pipe(uglify({
mangle: false
}))
.pipe(sourcemaps.write('./maps'))
.pipe(gulp.dest(jsDest))
.pipe(livereload());
});
/*jshint, watch, browserify*/
// configure the jshint task
gulp.task('jshint', ()=> {
return gulp.src(watch_hintJs)
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'));
});
gulp.task('browser-sync', gulp.series('sass', ()=> {
browserSync.init({
server: {
injectChanges: true,
baseDir: "./"
},
browser: ["chrome.exe"]
});
}));
gulp.task('js-watch', gulp.series('scripts', () =>{
console.log('you changed the JS');
return browserSync.reload();
}));
gulp.task('css-watch', gulp.series('sass', ()=> {
console.log('you changed the css');
return browserSync.reload();
}));
gulp.task('watch', gulp.series('browser-sync', ()=> {
console.log('you reach watch');
gulp.watch(watch_hintJs, ['js-watch']);
gulp.watch(watch_hintscss, ['css-watch']);
gulp.watch(watch_hintJs, browserSync.reload());
return livereload.listen();
}));
gulp.task('server', (done)=> {
return http.createServer(
st({
path: __dirname + '/',
index: 'index.html',
cache: false
})
).listen(8080, done);
});
var revts = require('gulp-rev-timestamp');
gulp.task('rev-timestamp', ()=> {
return gulp.src("./index.html")
.pipe(revts())
.pipe(gulp.dest('.'));
});
gulp.task('default', gulp.series('clean', 'css', 'sass', 'libs', 'scripts', 'rev-timestamp', 'watch'));
gulp.task('prod', gulp.series('clean', 'css', 'sass', 'libs', 'scripts', 'jshint', 'rev-timestamp'));
Note: Style task is working correctly and moving all .scss files from source to destination.
I really appreciate any help since I am running out of ideas
Finally, I found the solution as below:-
gulp.task('watch', ()=> {
console.log('you reach watch');
gulp.watch(watch_hintJs).on('change',gulp.parallel('js-watch'));
gulp.watch(watch_hintscss).on('change',gulp.parallel('css-watch'));
return livereload.listen();
});
I am new to Gulp watch and I'm facing the issue of Browsersync that is only refreshed for first time only when I run the "gulp watch" command and it only works for HTML,CSS files but not for scripts.js files.
I made this change on glop-watcher/index file
function onChange() {
console.log("onChange running: ", running); // custom changing
if (running) {
if (opt.queue) {
queued = true;
}
// custom changing
setTimeout(() => {
runComplete({msg: "custom code is working"});
}, 2000);
return;
}
now its refreshed the HTML,CSS file but still not working for scripts.js file at all even if refresh manually. Please help
Here is my gulpfile.js file
var gulp = require('gulp'),
settings = require('./settings'),
webpack = require('webpack'),
browserSync = require('browser-sync').create(),
postcss = require('gulp-postcss'),
rgba = require('postcss-hexrgba'),
autoprefixer = require('autoprefixer'),
cssvars = require('postcss-simple-vars'),
nested = require('postcss-nested'),
cssImport = require('postcss-import'),
mixins = require('postcss-mixins'),
colorFunctions = require('postcss-color-function');
gulp.task('styles', function() {
return gulp.src(settings.themeLocation + 'css/style.css')
.pipe(postcss([cssImport, mixins, cssvars, nested, rgba, colorFunctions, autoprefixer]))
.on('error', (error) => console.log(error.toString()))
.pipe(gulp.dest(settings.themeLocation));
});
gulp.task('scripts', function(callback) {
webpack(require('./webpack.config.js'), function(err, stats) {
if (err) {
console.log(err.toString());
}
console.log(stats.toString());
callback();
});
});
gulp.task('watch', function() {
browserSync.init({
notify: false,
proxy: settings.urlToPreview,
ghostMode: false
});
gulp.watch('./**/*.php', function() {
browserSync.reload();
});
gulp.watch(settings.themeLocation + 'css/**/*.css', gulp.parallel('waitForStyles'));
gulp.watch([settings.themeLocation + 'js/modules/*.js', settings.themeLocation + 'js/scripts.js'], gulp.parallel('waitForScripts'));
});
gulp.task('waitForStyles', gulp.series('styles', function() {
return gulp.src(settings.themeLocation + 'style.css')
.pipe(browserSync.stream());
}))
gulp.task('waitForScripts', gulp.series('scripts', function(cb) {
browserSync.reload();
cb()
}))
Finally, after 2 weeks of drilling into gulp I found the problem and solution too.
Here is the path of my .js files that gulp is watching
" .\myProject\wp-content\themes\myProject-theme\js "
but for gulp watch the path should be like this
" ./wp-content/themes/myProject-theme/js/*.js "
It does not include the main folder name/ root folder name. In my case the root folder where all my wordpress files lives is " myProject " and I mistakenly wrote it in gulp path that trouble me so much.
So be sure about your paths and also add this in onChange() function of glop-watcher/index file that is in the node_modules folder.
function onChange() {
console.log("onChange running: ", running);
if (running) {
if (opt.queue) {
queued = true;
}
// Add this code
setTimeout(() => {
runComplete({msg: "custom code is working"});
}, 2000);
return;
}
I am working on a small project that needs .sass files compiled into .css files. I have used Gulp a while ago and loved it, but my old gulpfile.js does not work anymore, because Gulp has changed since version 4.
I have made a new gulpfile.js:
var gulp = require('gulp'),
sass = require('gulp-sass'),
rename = require('gulp-rename');
var paths = {
styles: {
src: 'src/scss/*.scss',
dest: 'build/css'
}
};
function styles() {
return gulp
.src(paths.styles.src, {
sourcemaps: true
})
.pipe(sass())
.pipe(rename({
basename: 'main',
suffix: '.min'
}))
.pipe(gulp.dest(paths.styles.dest));
}
function watch() {
gulp
.watch(paths.styles.src, styles);
}
var syncConfig = {
server: {
baseDir : './',
index : 'index.html'
},
port : 3000,
open : false
};
// browser-sync
function server() {
init(syncConfig);
}
var build = gulp.parallel(styles, watch, server);
gulp
.task(build);
gulp
.task('default', build);
I have a "Did you forget to signal async completion?" error returned by the console.
Where is my mistake?
There ware two things missing: the browsersync variable browsersync = require('browser-sync').create() and the callback for the server function:
function server(done) {
if (browsersync) browsersync.init(syncConfig);
done();
}
It compiles SASS to CSS, still there is this problem: the page does not reload automatically when changes are made in the main.scss.
Here is the entire code:
var gulp = require('gulp'),
browsersync = require('browser-sync').create(),
sass = require('gulp-sass'),
rename = require('gulp-rename');
var paths = {
styles: {
src: 'src/scss/*.scss',
dest: 'build/css'
}
};
function styles() {
return gulp
.src(paths.styles.src, {
sourcemaps: true
})
.pipe(sass())
.pipe(rename({
basename: 'main',
suffix: '.min'
}))
.pipe(gulp.dest(paths.styles.dest));
}
function watch() {
gulp
.watch(paths.styles.src, styles);
}
var syncConfig = {
server: {
baseDir : './',
index : 'index.html'
},
port : 3000,
open : false
};
// browser-sync
function server(done) {
if (browsersync) browsersync.init(syncConfig);
done();
}
var build = gulp.parallel(styles, watch, server);
gulp
.task(build);
gulp
.task('default', build);
I can save two or three times on my editor and browsersync reloads. After 1 or 2 saves with same code gulp gives me this error
events.js:167
throw er; // Unhandled 'error' event
^
Error: assets\css\main.scss
Error: File to import not found or unreadable: 2-modules/header.
on line 10 of assets/css/main.scss
>> #import '2-modules/header';
^
at options.error (C:\Users\wfjcu\Documents\GitHub\lig\node_modules\node-sass\lib\index.js:291:26)
Emitted 'error' event at:
at DestroyableTransform.onerror (C:\Users\wfjcu\Documents\GitHub\lig\node_modules\vinyl-fs\node_modules\readable-stream\lib\_stream_readable.js:558:12)
at DestroyableTransform.emit (events.js:182:13)
at onwriteError (C:\Users\wfjcu\Documents\GitHub\lig\node_modules\through2\node_modules\readable-stream\lib\_stream_writable.js:356:10)
at onwrite (C:\Users\wfjcu\Documents\GitHub\lig\node_modules\through2\node_modules\readable-stream\lib\_stream_writable.js:373:11)
at WritableState.onwrite (C:\Users\wfjcu\Documents\GitHub\lig\node_modules\through2\node_modules\readable-stream\lib\_stream_writable.js:126:5)
at afterTransform (C:\Users\wfjcu\Documents\GitHub\lig\node_modules\through2\node_modules\readable-stream\lib\_stream_transform.js:81:3)
at TransformState.afterTransform (C:\Users\wfjcu\Documents\GitHub\lig\node_modules\through2\node_modules\readable-stream\lib\_stream_transform.js:58:12)
at errorM (C:\Users\wfjcu\Documents\GitHub\lig\node_modules\gulp-sass\index.js:118:12)
at Object.callback (C:\Users\wfjcu\Documents\GitHub\lig\node_modules\gulp-sass\index.js:127:16)
at options.error (C:\Users\wfjcu\Documents\GitHub\lig\node_modules\node-sass\lib\index.js:294:32)
This is the gulpfile.js this seems to be working fine before. But when i upgraded to gulp 4 it didnt and I reverted back to gulp 3.9.1 it gives the error when saving on sublime.
var gulp = require('gulp');
var browserSync = require('browser-sync');
var sass = require('gulp-sass');
var prefix = require('gulp-autoprefixer');
var cp = require('child_process');
var pug = require('gulp-pug');
var jekyll = process.platform === 'win32' ? 'jekyll.bat' : 'jekyll';
var messages = {
jekyllBuild: '<span style="color: grey">Running:</span> $ jekyll build'
};
/**
* Build the Jekyll Site
*/
gulp.task('jekyll-build', function (done) {
browserSync.notify(messages.jekyllBuild);
return cp.spawn( jekyll , ['build'], {stdio: 'inherit'})
.on('close', done);
});
/**
* Rebuild Jekyll & do page reload
*/
gulp.task('jekyll-rebuild', ['jekyll-build'], function () {
browserSync.reload();
});
/**
* Wait for jekyll-build, then launch the Server
*/
gulp.task('browser-sync', ['sass', 'jekyll-build'], function() {
browserSync({
server: {
baseDir: '_site'
},
notify: false
});
});
/**
* Compile files from _scss into both _site/css (for live injecting) and site (for future jekyll builds)
*/
gulp.task('sass', function () {
return gulp.src('assets/css/main.scss')
.pipe(sass({
includePaths: ['css'],
onError: browserSync.notify
}))
.pipe(prefix(['last 15 versions', '> 1%', 'ie 8', 'ie 7'], { cascade: true }))
.pipe(gulp.dest('_site/assets/css'))
.pipe(browserSync.reload({stream:true}))
.pipe(gulp.dest('assets/css'));
});
/**
* Compile files from _pugfiles into _includes (for live injecting) and site (for future jekyll builds)
*/
gulp.task('pug', function(){
return gulp.src('_pugfiles/*.pug')
.pipe(pug())
.pipe(gulp.dest('_includes'));
});
/**
* Watch scss files for changes & recompile
* Watch html/md files/pug files, run jekyll & reload BrowserSync
*/
gulp.task('watch', function () {
gulp.watch('assets/css/**', ['sass']);
gulp.watch(['*.html', '_layouts/*.html', '_includes/*'], ['jekyll-rebuild']);
gulp.watch(['_pugfiles/*.pug'], ['pug']);
});
/**
* Default task, running just `gulp` will compile the sass,
* compile the jekyll site, launch BrowserSync & watch files.
*/
gulp.task('default', ['browser-sync', 'watch']);
node version 10.4.1
npm version 6.4.1
gulp CLI 3.9.1
gulp Local 3.9.1