I am trying to create a gulpfile.js to compile scss to css and JS components to a main JS file. But it's not working properly.
The issues i am facing, when I run the command gulp:
It doesn't compile JS components to a main JS file.
It compiles SCSS but when i save any file, the git-bash terminal executing files infinitely, here is the screenshot:
Here is my gulpfile.js:
"use strict";
const source = 'assets/';
// Load Modules
const { src, dest, watch, series } = require('gulp');
const sass = require('gulp-sass')(require('sass'));
const postcss = require('gulp-postcss');
const cssnano = require('cssnano');
const terser = require('gulp-terser');
const browsersync = require('browser-sync').create();
// Scss Task
function scssTask() {
return src(`${source}/scss/zaincss.scss`)
.pipe(sass())
.pipe(postcss([cssnano()]))
.pipe(dest(`${source}/css`));
}
// Javascript Task
function jsTask() {
return src(`${source}/js/scripts/*.js`)
.pipe(terser())
.pipe(dest(`${source}/js/scripts/`));
}
// BrowserSync Tasks
function browserSyncServe(done) {
browsersync.init({
server: {
baseDir: '.'
},
injectChanges: true
});
done()
}
function browserSyncReload(done) {
browsersync.reload();
done();
}
// Watch Task
function watchTask() {
watch('*.html', browserSyncReload);
watch(['assets/scss/**/*.scss', 'assets/js/**/*.js'], series(scssTask, jsTask, browserSyncReload));
}
// Default Gulp Task
exports.default = series(
scssTask, jsTask, browserSyncServe, watchTask
);
I have googled a lot, but i am stuck. Please help me.
Part of the problem is you are watching the same directory that you are storing your js files in:
// Javascript Task
function jsTask() {
return src(`${source}/js/scripts/*.js`)
.pipe(terser())
.pipe(dest(`${source}/js/scripts/`));
}
So you send the files to ${source}/js/scripts/ but you are watching that location in your watch task: 'assets/js/**/*.js'. So any change in that location starts the process all over again.
Store you minified js files someplace else than the same directory you are watching for changes.
Related
I'm a tad lost on why my gulp tasks aren't running when a file is changed. In the console, it's detected the change but it's not actually re-running the tasks. Fairly new to gulp, so would love a little help.
const gulp = require('gulp');
const sass = require('gulp-sass')(require('sass'));
const autoprefixer = require('gulp-autoprefixer');
const browserSync = require('browser-sync').create();
const cleanCSS = require('gulp-clean-css');
const concat = require('gulp-concat');
const babel = require('gulp-babel');
const uglify = require('gulp-uglify');
// Compile Sass files and add vendor prefixes
function style() {
return gulp
.src('public/assets/css/*.css') // Source files
.pipe(sass().on('error', sass.logError)) // Compile Sass to CSS
.pipe(autoprefixer()) // Add vendor prefixes
.pipe(cleanCSS()) // Minify CSS
.pipe(concat('styles.css'))
.pipe(gulp.dest('public/source/css')) // Output to destination folder
.pipe(browserSync.stream()); // Inject changes into the browser
}
function scripts() {
return gulp
.src('public/assets/js/*.js')
.pipe(babel({
presets: ['#babel/env']
}))
.pipe(uglify()) // Minify JavaScript
.pipe(concat('scripts.min.js'))
.pipe(gulp.dest('public/source/js'))
.pipe(browserSync.stream());
}
// Watch for changes in source files
function watch() {
browserSync.init({
proxy: "gif-ddev.ddev.site", // Your DDEV site URL
files: ["public/assets/css/*.css", "public/assets/js/*.js"],
open: true,
});
gulp.watch('public/assets/css/*.css', style); // Watch CSS files
gulp.watch('public/assets/js/*.js', scripts); // Watch JS files
gulp.watch(['templates/*.html', 'templates/**/*.twig']).on('change', browserSync.reload); // Watch HTML and Twig files
}
exports.style = style; // Expose the style task
exports.scripts = scripts;
exports.watch = watch; // Expose the watch task
Was the bugged line about twig and templates. Such a pain. Removing this fixed the issue.
So I have two gulpfiles in this site I'm working on, one for the whole project which only watches and compiles sass and one inside a Foundation Emails project which is kept in a subdirectory in the project. When I try running any scripts or gulp tasks inside this Foundation subdirectory it runs the default task of the outer gulpfile. How can I make it so that when I'm in the subdirectory it only uses that gulpfile?
Outermost gulpfile:
var gulp = require('gulp');
var sass = require('gulp-sass');
var watch = require('gulp-watch');
var autoprefixer = require('gulp-autoprefixer');
gulp.task('default', function() {
return watch('ps_app/public/sass/*.scss')
.pipe(sass())
.pipe(autoprefixer())
.pipe(gulp.dest('ps_app/public/css/custom'));
});
gulp.task('sass', function() {
return gulp.src('ps_app/public/sass/*.scss')
.pipe(sass())
.pipe(autoprefixer())
.pipe(gulp.dest('ps_app/public/css/custom'));
});
Foundation Emails Subdirectory gulpfile:
import gulp from 'gulp';
import plugins from 'gulp-load-plugins';
import browser from 'browser-sync';
import rimraf from 'rimraf';
import panini from 'panini';
import yargs from 'yargs';
import lazypipe from 'lazypipe';
import inky from 'inky';
import fs from 'fs';
import siphon from 'siphon-media-query';
import path from 'path';
import merge from 'merge-stream';
import beep from 'beepbeep';
import colors from 'colors';
const $ = plugins();
// Look for the --production flag
const PRODUCTION = !!(yargs.argv.production);
// Declar var so that both AWS and Litmus task can use it.
var CONFIG;
// Build the "dist" folder by running all of the above tasks
gulp.task('build',
gulp.series(clean, pages, sass, images, inline));
// Build emails, run the server, and watch for file changes
gulp.task('default',
gulp.series('build', server, watch));
// Build emails, then send to litmus
gulp.task('litmus',
gulp.series('build', creds, aws, litmus));
// Build emails, then zip
gulp.task('zip',
gulp.series('build', zip));
// Delete the "dist" folder
// This happens every time a build starts
function clean(done) {
rimraf('dist', done);
}
// Compile layouts, pages, and partials into flat HTML files
// Then parse using Inky templates
function pages() {
return gulp.src('src/pages/**/*.html')
.pipe(panini({
root: 'src/pages',
layouts: 'src/layouts',
partials: 'src/partials',
helpers: 'src/helpers'
}))
.pipe(inky())
.pipe(gulp.dest('dist'));
}
// Reset Panini's cache of layouts and partials
function resetPages(done) {
panini.refresh();
done();
}
// Compile Sass into CSS
function sass() {
return gulp.src('src/assets/scss/app.scss')
.pipe($.if(!PRODUCTION, $.sourcemaps.init()))
.pipe($.sass({
includePaths: ['node_modules/foundation-emails/scss']
}).on('error', $.sass.logError))
.pipe($.if(!PRODUCTION, $.sourcemaps.write()))
.pipe(gulp.dest('dist/css'));
}
// Copy and compress images
function images() {
return gulp.src('src/assets/img/**/*')
.pipe($.imagemin())
.pipe(gulp.dest('./dist/assets/img'));
}
// Inline CSS and minify HTML
function inline() {
return gulp.src('dist/**/*.html')
.pipe($.if(PRODUCTION, inliner('dist/css/app.css')))
.pipe(gulp.dest('dist'));
}
// Start a server with LiveReload to preview the site in
function server(done) {
browser.init({
server: 'dist'
});
done();
}
// Watch for file changes
function watch() {
gulp.watch('src/pages/**/*.html').on('change', gulp.series(pages, inline, browser.reload));
gulp.watch(['src/layouts/**/*', 'src/partials/**/*']).on('change', gulp.series(resetPages, pages, inline, browser.reload));
gulp.watch(['../scss/**/*.scss', 'src/assets/scss/**/*.scss']).on('change', gulp.series(resetPages, sass, pages, inline, browser.reload));
gulp.watch('src/assets/img/**/*').on('change', gulp.series(images, browser.reload));
}
// Inlines CSS into HTML, adds media query CSS into the <style> tag of the email, and compresses the HTML
function inliner(css) {
var css = fs.readFileSync(css).toString();
var mqCss = siphon(css);
var pipe = lazypipe()
.pipe($.inlineCss, {
applyStyleTags: false,
removeStyleTags: false,
removeLinkTags: false
})
.pipe($.replace, '<!-- <style> -->', `<style>${mqCss}</style>`)
.pipe($.replace, '<link rel="stylesheet" type="text/css" href="css/app.css">', '')
.pipe($.htmlmin, {
collapseWhitespace: true,
minifyCSS: true
});
return pipe();
}
// Ensure creds for Litmus are at least there.
function creds(done) {
var configPath = './config.json';
try { CONFIG = JSON.parse(fs.readFileSync(configPath)); }
catch(e) {
beep();
console.log('[AWS]'.bold.red + ' Sorry, there was an issue locating your config.json. Please see README.md');
process.exit();
}
done();
}
// Post images to AWS S3 so they are accessible to Litmus test
function aws() {
var publisher = !!CONFIG.aws ? $.awspublish.create(CONFIG.aws) : $.awspublish.create();
var headers = {
'Cache-Control': 'max-age=315360000, no-transform, public'
};
return gulp.src('./dist/assets/img/*')
// publisher will add Content-Length, Content-Type and headers specified above
// If not specified it will set x-amz-acl to public-read by default
.pipe(publisher.publish(headers))
// create a cache file to speed up consecutive uploads
//.pipe(publisher.cache())
// print upload updates to console
.pipe($.awspublish.reporter());
}
// Send email to Litmus for testing. If no AWS creds then do not replace img urls.
function litmus() {
var awsURL = !!CONFIG && !!CONFIG.aws && !!CONFIG.aws.url ? CONFIG.aws.url : false;
return gulp.src('dist/**/*.html')
.pipe($.if(!!awsURL, $.replace(/=('|")(\/?assets\/img)/g, "=$1"+ awsURL)))
.pipe($.litmus(CONFIG.litmus))
.pipe(gulp.dest('dist'));
}
// Copy and compress into Zip
function zip() {
var dist = 'dist';
var ext = '.html';
function getHtmlFiles(dir) {
return fs.readdirSync(dir)
.filter(function(file) {
var fileExt = path.join(dir, file);
var isHtml = path.extname(fileExt) == ext;
return fs.statSync(fileExt).isFile() && isHtml;
});
}
var htmlFiles = getHtmlFiles(dist);
var moveTasks = htmlFiles.map(function(file){
var sourcePath = path.join(dist, file);
var fileName = path.basename(sourcePath, ext);
var moveHTML = gulp.src(sourcePath)
.pipe($.rename(function (path) {
path.dirname = fileName;
return path;
}));
var moveImages = gulp.src(sourcePath)
.pipe($.htmlSrc({ selector: 'img'}))
.pipe($.rename(function (path) {
path.dirname = fileName + '/assets/img';
return path;
}));
return merge(moveHTML, moveImages)
.pipe($.zip(fileName+ '.zip'))
.pipe(gulp.dest('dist'));
});
return merge(moveTasks);
}
The specific tasks I run are npm start and npm run build which do these tasks in my package.json in the same subdirectory as the Foundation Emails:
"scripts": {
"start": "gulp",
"build": "gulp --production",
"zip": "gulp zip --production",
"litmus": "gulp litmus --production"
},
Thank you for any help you can give.
You can use the --gulpfile CLI parameter to manually specify the gulpfile:
--gulpfile <gulpfile path> will manually set path of gulpfile. Useful if you have multiple gulpfiles. This will set the CWD to the gulpfile directory as well
Source
I know that this can be a very stupid question, but I can't find matches with other posts on stackoverflow...
So: Can I modify a file of an external module , just save the file and do something that my app can listen?
At the moment, i'm trying ti change some scss style at the ng2-datepicker module (inside node_modules folder), but if I save and the launch ng serve, changes will not affect my project.
I know it's a simple problem, but i don't know the background architecture of an Angular2 project.
Thanks in advance.
(ps I've seen that i can fork the git and then do something like npm install.
Very interesting, but i also want to know how to have the same result in local)
If you are using gulp file you can tell the changed lib file path to copy to build folder check gulp.task('copy-libs') in code below git repo for angular2-tour-of-heroes using gulp
const gulp = require('gulp');
const del = require('del');
const typescript = require('gulp-typescript');
const tscConfig = require('./tsconfig.json');
const sourcemaps = require('gulp-sourcemaps');
const tslint = require('gulp-tslint');
const browserSync = require('browser-sync');
const reload = browserSync.reload;
const tsconfig = require('tsconfig-glob');
// clean the contents of the distribution directory
gulp.task('clean', function () {
return del('dist/**/*');
});
// copy static assets - i.e. non TypeScript compiled source
gulp.task('copy:assets', ['clean'], function() {
return gulp.src(['app/**/*', 'index.html', 'styles.css', '!app/**/*.ts'], { base : './' })
.pipe(gulp.dest('dist'))
});
// copy dependencies
gulp.task('copy:libs', ['clean'], function() {
return gulp.src([
'node_modules/angular2/bundles/angular2-polyfills.js',
'node_modules/systemjs/dist/system.src.js',
'node_modules/rxjs/bundles/Rx.js',
'node_modules/angular2/bundles/angular2.dev.js',
'node_modules/angular2/bundles/router.dev.js',
'node_modules/node-uuid/uuid.js',
'node_modules/immutable/dist/immutable.js'
'yourpath/changedFileName.js'
])
.pipe(gulp.dest('dist/lib'))
});
// linting
gulp.task('tslint', function() {
return gulp.src('app/**/*.ts')
.pipe(tslint())
.pipe(tslint.report('verbose'));
});
// TypeScript compile
gulp.task('compile', ['clean'], function () {
return gulp
.src(tscConfig.files)
.pipe(sourcemaps.init())
.pipe(typescript(tscConfig.compilerOptions))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('dist/app'));
});
// update the tsconfig files based on the glob pattern
gulp.task('tsconfig-glob', function () {
return tsconfig({
configPath: '.',
indent: 2
});
});
// Run browsersync for development
gulp.task('serve', ['build'], function() {
browserSync({
server: {
baseDir: 'dist'
}
});
gulp.watch(['app/**/*', 'index.html', 'styles.css'], ['buildAndReload']);
});
gulp.task('build', ['tslint', 'compile', 'copy:libs', 'copy:assets']);
gulp.task('buildAndReload', ['build'], reload);
gulp.task('default', ['build']);
I'm attempting to use browser-sync with Gulp 4, but bs is not preserving state, and instead does a full refresh. This is not very useful. It seems bs no longer supports true injection. I filed an issue on GH if you want to contribute.
Here is the pertinent code:
// styles:dev task
gulp.task('styles:dev', function() {
return gulp.src(config.src)
.pipe(sourcemaps.init())
.pipe(postcss(config.postcss.dev))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(config.dest.dev))
.pipe(browserSync.stream());
});
// browserSync task
gulp.task('browserSync', function(cb) {
browserSync.init(config, cb);
});
// Watch task:
gulp.task('watch:styles', function() {
return gulp.watch(config.paths.css,
gulp.series('styles:dev'));
});
gulp.task('watch', gulp.parallel('watch:styles'));
// default task
gulp.task('default',
gulp.series('clean:dev',
gulp.parallel('copy:dev', 'styles:dev'), 'browserSync', 'watch')
);
Thanks in advance.
Fixed. Here's where I went wrong:
The browser-sync constructor takes an options object, which can include a files array. Most of the tutorials I've read, including the gulpfile for Google's very own Web Starter Kit, do not include this. As it turns out, this is required for style injection to preserve state.
Furthermore, do not pass .stream() or .reload() as the final pipe in your styles task. It is not needed, and will short circuit style injection, forcing a full refresh.
Finally, the browserSync process must not be terminated, and watch and browserSync tasks must execute in parallel in order for live style injection to take place.
Hope this helps anybody facing this issue.
I also closed the corresponding github issue, and posted my gulpfile
Almost 3 years later Gulp 4 now looks a little bit different, see https://gulpjs.com/docs/en/getting-started/creating-tasks
To have a complete Gulp 4 kickstart example, see https://gist.github.com/leymannx/8f6a75e8ad5055276a71d2901813726e
// Requires Gulp v4.
// $ npm uninstall --global gulp gulp-cli
// $ rm /usr/local/share/man/man1/gulp.1
// $ npm install --global gulp-cli
// $ npm install
const { src, dest, watch, series, parallel } = require('gulp');
const browsersync = require('browser-sync').create();
const sass = require('gulp-sass');
const autoprefixer = require('gulp-autoprefixer');
const sourcemaps = require('gulp-sourcemaps');
const plumber = require('gulp-plumber');
const sasslint = require('gulp-sass-lint');
const cache = require('gulp-cached');
// Compile CSS from Sass.
function buildStyles() {
return src('scss/ix_experience.scss')
.pipe(plumber()) // Global error listener.
.pipe(sourcemaps.init())
.pipe(sass({ outputStyle: 'compressed' }))
.pipe(autoprefixer(['last 15 versions', '> 1%', 'ie 8', 'ie 7']))
.pipe(sourcemaps.write())
.pipe(dest('css/'))
.pipe(browsersync.reload({ stream: true }));
}
// Watch changes on all *.scss files, lint them and
// trigger buildStyles() at the end.
function watchFiles() {
watch(
['scss/*.scss', 'scss/**/*.scss'],
{ events: 'all', ignoreInitial: false },
series(sassLint, buildStyles)
);
}
// Init BrowserSync.
function browserSync(done) {
browsersync.init({
proxy: 'blog.localhost', // Change this value to match your local URL.
socket: {
domain: 'localhost:3000'
}
});
done();
}
// Init Sass linter.
function sassLint() {
return src(['scss/*.scss', 'scss/**/*.scss'])
.pipe(cache('sasslint'))
.pipe(sasslint({
configFile: '.sass-lint.yml'
}))
.pipe(sasslint.format())
.pipe(sasslint.failOnError());
}
// Export commands.
exports.default = parallel(browserSync, watchFiles); // $ gulp
exports.sass = buildStyles; // $ gulp sass
exports.watch = watchFiles; // $ gulp watch
exports.build = series(buildStyles); // $ gulp build
Goal
I'm updating my old gulpfile.js, which used to be mainly for compiling my Sass into CSS, but now I'm trying to get Gulp to do the following:
Sync browser, whip up localhost server - DONE
Compile Sass => CSS - DONE
Show any JavaScript errors with JSHint - DONE
Compile ES6 => ES6 with Babel (WORKING ON)
Minify all assets (WORKING ON)
Show project file size - DONE
Deploy index.html, style.css and images to S3 (WORKING ON)
Watch files, reload browser when .scss or .html changes - DONE
Problem
Trying to minify my Javascript and also create a scripts.min.js
file, it keeps adding the suffix min to every new minified JavaScript
file.
Folder structure
index.html
gulpfile.js
package.json
.aws.json
.csscomb.json
.gitignore
assets
- css
style.css
style.scss
--partials
---base
---components
---modules
- img
- js
scripts.js
- dist
gulpfile.js
// Include Gulp
var gulp = require('gulp');
var postcss = require("gulp-postcss");
// All of your plugins
var autoprefixer = require('autoprefixer');
var browserSync = require('browser-sync');
var cache = require('gulp-cache');
var concat = require('gulp-concat');
var csswring = require("csswring");
var imagemin = require('gulp-imagemin');
var jshint = require('gulp-jshint');
var lost = require("lost");
var plumber = require('gulp-plumber');
var rename = require('gulp-rename');
var rucksack = require("rucksack-css");
var sass = require('gulp-sass');
var uglify = require('gulp-uglify');
// Sync browser, whip up server
gulp.task('browser-sync', function() {
browserSync({
server: {
baseDir: "./"
}
});
});
// Reload page automagically
gulp.task('bs-reload', function () {
browserSync.reload();
});
// Compile Sass into CSS, apply postprocessors
gulp.task('styles', function(){
var processors = [
autoprefixer({browsers: ['last 2 version']}),
csswring,
lost,
rucksack
];
gulp.src(['assets/css/**/*.scss'])
.pipe(plumber({
errorHandler: function (error) {
console.log(error.message);
this.emit('end');
}}))
.pipe(sass())
.pipe(postcss(processors))
// .pipe(gulp.dest('assets/css/'))
// .pipe(rename({suffix: '.min'}))
.pipe(gulp.dest('assets/css/'))
.pipe(browserSync.reload({stream:true}))
});
// Show any JavaScript errors
gulp.task('scripts', function(){
return gulp.src('assets/js/**/*.js')
.pipe(plumber({
errorHandler: function (error) {
console.log(error.message);
this.emit('end');
}}))
.pipe(jshint())
.pipe(jshint.reporter('default'))
// .pipe(concat('main.js'))
// .pipe(babel())
.pipe(gulp.dest('assets/js/'))
.pipe(uglify())
.pipe(gulp.dest('assets/js/'))
.pipe(rename({suffix: '.min'}))
.pipe(browserSync.reload({stream:true}))
});
// Minify assets, create build folder
gulp.task('images', function(){
gulp.src('assets/img/**/*')
.pipe(cache(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })))
.pipe(gulp.dest('assets/img'));
});
// Minify HTML
// Default task
gulp.task('default', ['browser-sync'], function(){
gulp.watch("assets/css/**/*.scss", ['styles']);
gulp.watch("assets/js/**/*.js", ['scripts']);
gulp.watch("*.html", ['bs-reload']);
gulp.start("images", "styles", "scripts")
});
// var babel = require('gulp-babel');
// var minifyhtml = require("gulp-minify-html");
// var size = require("gulp-size");
// var upload = require("gulp-s3");
Hi i can't solve all your problems but I had also a similar issue with the babel and ES6 fat arrow functions (using babelify and browserify). To solve the problem try to pass:
stage: 0
to your babel.js gulp plugin. If error will still occurs then try to pass also:
experimental: true
For more information please have a look "experimental" section on babel.js site.