We have recently switched from using a PHP asset manager to Gulp. We use bower to pull in our frontend packages and their dependencies.
Using simple Bower packages that only have JS files listed in 'main' is pretty straightforward and is easily done.
Using 'main-bower-files' we grab the required js files and concatenate them into one script file which we send to our site/script folder.
The fonts we can collect and move to a fonts/ folder in our site.
Then we hit a wall... What to do with images and their paths in the corresponding css/scss files.
To further complicate things we want images to keep some of their original folder layout so they don't get overridden.
We want to grab the css and scss (we use libsass) files and merge them with our own styles into one .css file.
But how can we make sure they still have working paths to the images that come with them.
The desired folder layout is as follows:
bower.json
gulpfile.js
package.json
bower_components/
site/
- css/styles.css
- fonts/
- images/
- bower-package-a/
- arrow.png
- gradient.png
- themea-a/
- arrow.png
- theme-b/
- arrow.png
- bower-package-b/
- arrow.png
- gradient.png
- script/
This is our Gulpfile so far:
// Include gulp
var gulp = require('gulp');
// Include Plugins
var bower = require('gulp-bower');
var browserSync = require('browser-sync').create();
var concat = require('gulp-concat');
var del = require('del');
var filter = require('gulp-filter');
var gutil = require('gulp-util');
var imagemin = require('gulp-imagemin');
var jshint = require('gulp-jshint');
var mainBowerFiles = require('main-bower-files');
var merge = require('merge-stream');
var newer = require('gulp-newer');
var plumber = require('gulp-plumber');
var pngquant = require('imagemin-pngquant');
var rename = require('gulp-rename');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var changed = require('gulp-changed');
var parallel = require("concurrent-transform");
var os = require("os");
var imageResize = require('gulp-image-resize');
var spritesmith = require('gulp.spritesmith');
var uglify = require('gulp-uglify');
// Paden
var bowerDest = 'site/script/lib/bower';
var imgSrc = 'src/images/**';
var imgDest = 'site/images';
var spriteImgDest = './src/images/sprite/';
var scriptSrc = 'src/script/**/*.js';
var scriptDest = 'site/script';
var stylesSrc = 'src/styles/styles.scss';
var stylesDest = 'site/css';
// Helpers
var onSassError = function(error) {
gutil.log('Sass Error', gutil.colors.red('123'));
gutil.beep();
console.log(error);
this.emit('end');
}
// Clean images Task
gulp.task('clean:images', function () {
return del([imgDest]);
});
// Clean script Task
gulp.task('clean:script', function () {
return del([scriptDest]);
});
// Clean image Task
gulp.task('clean:styles', function () {
return del([stylesDest]);
});
// Lint Task
gulp.task('lint', function() {
return gulp.src(scriptSrc)
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'))
;
});
// Sass Task
gulp.task('sass', ['sprite'], function() {
return gulp.src(stylesSrc)
.pipe(plumber({
errorHandler: onSassError
}))
.pipe(sourcemaps.init())
.pipe(sass({
includePaths: [
'bower_components/compass-mixins/lib',
'bower_components/foundation/scss'
],
outputStyle: 'compressed'
}))
.pipe(sourcemaps.write('./map'))
.pipe(gulp.dest(stylesDest))
.pipe(browserSync.stream())
;
});
// Concatenate & Minify JS
gulp.task('script', function() {
return gulp.src(scriptSrc)
.pipe(concat('script.js'))
.pipe(gulp.dest(scriptDest))
.pipe(rename('script.min.js'))
.pipe(uglify())
.pipe(gulp.dest(scriptDest))
;
});
// Voeg de JS bestanden die gebruikt worden vanuit bower samen. Let op: modernizr volgt niet de standaard
// en wordt daarom niet meegenomen in mainBowerFiles(). Deze voegen we dus los toe.
gulp.task('bower:js', function() {
var modernizr = gulp.src('bower_components/modernizr/modernizr.js')
.pipe(rename('modernizr.min.js'))
.pipe(uglify())
.pipe(gulp.dest(scriptDest))
;
var frontend = gulp.src(mainBowerFiles())
.pipe(sourcemaps.init())
.pipe(filter('*.js'))
.pipe(concat('frontend.min.js'))
.pipe(uglify())
.pipe(sourcemaps.write('maps'))
.pipe(gulp.dest(scriptDest))
;
return merge(modernizr, frontend);
});
// Imagemin Task (compress images)
gulp.task('imagemin', function () {
return gulp.src([imgSrc, '!src/images/sprite{,/**}'])
.pipe(newer(imgDest))
.pipe(imagemin({
use: [pngquant()]
}))
.pipe(gulp.dest(imgDest))
.pipe(browserSync.stream())
;
});
// Compile sass into CSS & auto-inject into browsers
gulp.task('browser-sync', function() {
// Serve files from the root of this project
browserSync.init({
proxy: "localhost/insyde/website_v6_devtools/site"
});
// add browserSync.reload to the tasks array to make
// all browsers reload after tasks are complete.
gulp.watch("./src/script/**/*.js", ['scripts-watch']);
});
// generate the x1 images from the big ones
gulp.task('generate-small-sprite-images', function () {
return gulp.src('./src/images/sprite/*-2x.png')
.pipe(newer(rename(function(path) {
path.basename = path.basename.slice(0, -3); //remove #2x label
})))
.pipe(parallel(
imageResize({
width: '50%',
height: '50%'
}), os.cpus().length
))
.pipe(rename(function(path) {
path.basename = path.basename.slice(0, -3); //remove #2x label
}))
.pipe(gulp.dest(spriteImgDest))
;});
gulp.task('sprite', ['generate-small-sprite-images'], function () {
var spriteData = gulp.src('./src/images/sprite/**/*.png').pipe(spritesmith({
imgName: 'sprite.png',
retinaImgName: 'sprite-2x.png',
cssName: 'sprite.scss',
imgPath: '../images/sprite.png',
retinaImgPath : '../images/sprite-2x.png',
retinaSrcFilter: '**/*-2x.png'
}));
// Pipe image stream through image optimizer and onto disk
var imgStream = spriteData.img
.pipe(imagemin())
.pipe(gulp.dest(imgDest));
// Pipe CSS stream through CSS optimizer and onto disk
var cssStream = spriteData.css
.pipe(gulp.dest('./src/styles/'));
// Return a merged stream to handle both `end` events
return merge(imgStream, cssStream);
});
// Watch Files For Changes
gulp.task('watch', function() {
gulp.watch('./src/script/**/*.js', ['lint', 'script']);
gulp.watch('./src/styles/**/*.scss', ['sass']);
gulp.watch('./src/images/**', ['imagemin']);
gulp.watch('./templates/**/*.html').on('change', browserSync.reload);
});
// Default Tasks
gulp.task('default', ['lint', 'sass', 'bower:js', 'script', 'imagemin', 'watch']);
gulp.task('frontend', ['lint', 'sprite', 'sass', 'bower:js', 'script', 'imagemin', 'browser-sync', 'watch']);
gulp.task('clean', ['clean:images', 'clean:script', 'clean:styles']);
// create a task that ensures the `scripts` task is complete before
// reloading browsers
gulp.task('scripts-watch', ['script'], browserSync.reload);
Got it working!
I used this as an example: https://github.com/jonkemp/gulp-useref/issues/60#issuecomment-77535822
What these tasks do is:
bower:assets
Copy all asset files (images and fonts) that are defined in the 'main' property of bower packages (which we find by using main-bower-files) to site/dist/ while keeping the original folder layout of the packages themself.
bower:styles
Parse each stylesheet that comes from main-bower-files (excluding two packages: foundation and compass-mixins) and rework the urls that point to the images and fonts that we copied earlier. This differs from the example in a way that the files in my situation aren't first copied to a .tmp directory, but get dealed with and then written to the site/css folder directly. I concatenate and minify the css, while using sourcemaps to make debugging easier.
//copy bower assets that need copying
gulp.task('bower:assets', function() {
return gulp.src(mainBowerFiles(), {
base: './bower_components'
})
.pipe(filter([
'**/*.{png,gif,svg,jpeg,jpg,woff,eot,ttf}',
'!foundation/**/*',
'!compass-mixins/**/*'
]))
.pipe(gulp.dest('./site/dist'));
});
//generate bower stylesheets with correct asset paths
gulp.task('bower:styles', function() {
return gulp.src(mainBowerFiles(), {
base: './bower_components'
})
.pipe(filter([
'**/*.{css,scss}',
'!foundation/**/*',
'!compass-mixins/**/*'
]))
.pipe(foreach(function(stream, file) {
var dirName = path.dirname(file.path);
return stream
.pipe(rework(reworkUrl(function(url) {
var fullUrl = path.join(dirName, url);
if (fs.existsSync(fullUrl)) {
bowerCopyFiles.push(fullUrl);
console.log(path.relative('css', fullUrl).replace(/bower_components/, 'dist'));
return path.relative('css', fullUrl).replace(/bower_components/, 'dist');
}
return url;
})));
}))
.pipe(sourcemaps.init())
.pipe(concat('bower.css'))
.pipe(minifyCss())
.pipe(sourcemaps.write('./map'))
.pipe(gulp.dest(stylesDest));
});
This all results in the following directory sturcture:
bower_components
site
css
bower.css
dist
bower-component-a
images
arrow.png
gradient.png
bower-component-b
images
arrow.png
gradient.png
Another option is to use the gulp-bower-normalize package, which will take the piped output from main-bower-files and then split them up based on the package and file extension, e.g.
gulp.src(mainBowerFiles(), { base: 'bower_components' })
.pipe(bowerNormalize({ bowerJson: './bower.json' }))
.pipe(gulp.dest('assets/vendor'));
You may have to tweak the main files in bower.js as well, but it works quite nicely. If you were using Bootstrap...
bower.json:
{
...
"dependencies": {
"bootstrap": "^3.3.6",
...
},
"overrides": {
"bootstrap": {
"main": [
"dist/css/bootstrap.min.css",
"dist/js/bootstrap.min.js",
"fonts/glyphicons-halflings-regular.eot",
"fonts/glyphicons-halflings-regular.svg",
"fonts/glyphicons-halflings-regular.ttf",
"fonts/glyphicons-halflings-regular.woff",
"fonts/glyphicons-halflings-regular.woff2"
],
"normalize": {
"fonts": ["*.eot", "*.svg", "*.ttf", "*.woff", "*.woff2"]
}
}
}
}
... it would generate the below structure:
assets/
|-- vendor/
|-- bootstrap/
|-- css/
| |-- bootstrap.min.css
|
|-- fonts/
| |-- glyphicons-halflings-regular.eot
| |-- glyphicons-halflings-regular.svg
| |-- glyphicons-halflings-regular.ttf
| |-- glyphicons-halflings-regular.woff
| |-- glyphicons-halflings-regular.woff2
|
|-- js/
|-- bootstrap.min.js
Another nice option it has is to flatten the structure, which may be more useful when bundling up vendor files.
Related
I need help with my gulp project. Drops me error in terminal: TypeError: parallel is not a function Already searched information whole internet. Answer is to update Gulp version to 4.0.. Already updated. still shows the "parallel function" issue
My file:
const { src, dest, parallel, series, watch } = import('gulp');
const twig = import('gulp-twig');
const sass = import('gulp-sass');
const prefix = import('gulp-autoprefixer');
const data = import('gulp-data');
const sourcemaps = import('gulp-sourcemaps');
const concat = import('gulp-concat');
const plumber = import('gulp-plumber');
const browsersync = import('browser-sync');
const gulpcopy = import('gulp-copy');
const fs = import('fs');
const del = import('del');
const path = import('path');
var paths = {
build: {
html: 'dist/',
js: 'dist/assets/js/',
css: 'dist/assets/css/',
img: 'dist/assets/img/',
fonts: 'dist/assets/fonts/',
icons: 'dist/assets/icons/',
json: 'dist/assets/'
},
src: {
html: 'src/*.{htm,html,php}',
js: 'src/assets/js/*.js',
css: 'src/assets/sass/style.scss',
img: 'src/assets/img/**/*.*',
fonts: 'src/assets/fonts/**/*.*',
icons: 'src/assets/icons/**/*.*',
json: 'src/assets/*.json'
},
watch: {
html: 'src/**/*.{htm,html,php}',
js: 'src/assets/js/**/*.js',
css: 'src/assets/sass/**/*.scss',
img: 'src/assets/img/**/*.*',
fonts: 'src/assets/fonts/**/*.*',
icons: 'src/assets/icons/**/*.*',
json: 'src/assets/*.json'
},
clean: './dist'
};
// SCSS bundled into CSS task
function css() {
return src('client/scss/vendors/*.scss')
.pipe(sourcemaps.init())
// Stay live and reload on error
.pipe(plumber({
handleError: function (err) {
console.log(err);
this.emit('end');
}
}))
.pipe(sass({
includePaths: [paths.src.css + 'vendors/'],
outputStyle: 'compressed'
}).on('error', function (err) {
console.log(err.message);
// sass.logError
this.emit('end');
}))
.pipe(prefix(['last 15 versions','> 1%','ie 8','ie 7','iOS >= 9','Safari >= 9','Android >= 4.4','Opera >= 30'], {
cascade: true
}))
//.pipe(minifyCSS())
.pipe(concat('bootstrap.min.css'))
.pipe(sourcemaps.write('.'))
.pipe(dest('build/assets/css'));
}
// JS bundled into min.js task
function js() {
return src('dist/js/*.js')
.pipe(sourcemaps.init())
.pipe(concat('scripts.min.js'))
.pipe(sourcemaps.write('.'))
.pipe(dest('build/assets/js'));
}
function twigTpl () {
return src(['./dist/templates/*.twig'])
// Stay live and reload on error
.pipe(plumber({
handleError: function (err) {
console.log(err);
this.emit('end');
}
}))
// Load template pages json data
.pipe(data(function (file) {
return JSON.parse(fs.readFileSync(paths.data + path.basename(file.path) + '.json'));
}).on('error', function (err) {
process.stderr.write(err.message + '\n');
this.emit('end');
})
)
// Load default json data
.pipe(data(function () {
return JSON.parse(fs.readFileSync(paths.data + path.basename('default.twig.json')));
}).on('error', function (err) {
process.stderr.write(err.message + '\n');
this.emit('end');
})
)
// Twig compiled
.pipe(twig()
.on('error', function (err) {
process.stderr.write(err.message + '\n');
this.emit('end');
})
)
.pipe(dest(paths.build));
}
function copyAssets() {
// Copy assets
return src(['./dist/assets/**/*.*','!./dist/assets/**/*.psd','!./dist/assets/**/*.*.map'],
del(paths.build + 'assets/**/*')
)
.pipe(gulpcopy(paths.build + 'assets', { prefix: 2 }));
}
// BrowserSync
function browserSync() {
browsersync({
server: {
baseDir: paths.build
},
notify: false,
browser: "google chrome",
// proxy: "0.0.0.0:5000"
});
}
// BrowserSync reload
function browserReload () {
return browsersync.reload;
}
// Watch files
function watchFiles() {
// Watch SCSS changes
watch(paths.scss + '**/*.scss', parallel(css))
.on('change', browserReload());
// Watch javascripts changes
watch(paths.js + '*.js', parallel(js))
.on('change', browserReload());
// Watch template changes
watch(['dist/templates/**/*.twig','dist/data/*.twig.json'], parallel(twigTpl))
.on('change', browserReload());
// Assets Watch and copy to build in some file changes
watch('dist/assets/**/*')
.on('change', series(copyAssets, css, css_vendors, js, browserReload()));
}
const watching = parallel(watchFiles, browserSync);
exports.js = js;
exports.css = css;
exports.default = parallel(copyAssets, css, js, twigTpl);
exports.watch = watching;
My gulp version:
"node": "18.12.1"
"gulp": "^4.0.2",
On terminal when i write gulp -v it shows:
CLI version: 2.3.0
Local version: 4.0.2
Expecting professional help
Since your gulpfile is a CommonJS module, use require instead of import:
const { src, dest, parallel, series, watch } = require('gulp');
const twig = require('gulp-twig');
const sass = require('gulp-sass');
const prefix = require('gulp-autoprefixer');
const data = require('gulp-data');
const sourcemaps = require('gulp-sourcemaps');
const concat = require('gulp-concat');
const plumber = require('gulp-plumber');
const browsersync = require('browser-sync');
const gulpcopy = require('gulp-copy');
const fs = require('fs');
const del = require('del');
const path = require('path');
Using an ESM style gulpfile is also an option, but it's not as simple as just replacing require with import (btw the syntax is import sass from 'gulp-sass';...), you will also need to rename the file to "gulpfile.mjs", change the style of your exports, and probably more.
I'm using gulp and I trying to create a gulp task that combine files in a javascript file.
For example, image I have this:
File template\template1.html :
<h2>some html content</h2>
<p>blah blah blah</p>
File template\template2.html :
<h2>some other html content</h2>
<img src='cat.png'>
I'd like to read and merge these files into a single javascript file like this :
const templates = {
"template1" : "<h2>some html content</h2>\n<p>blah blah blah</p>",
"template2" : "<h2>some other html content</h2>\n<img src='cat.png'>"
}
export default templates
However, I'm failing when dealing with gulp plumbing (I'm quite new to gulp I admit).
How to reach my goal ?
Right now I tried to play with gulp-trough, but it fails at execution:
const gulp = require('gulp');
const through = require('gulp-through');
gulp.task('templates', function () {
var result = {}
gulp.src('src/templates/**/*.html')
.pipe(through('readFile', function(){
console.log(arguments); // not reached!
}, defaults));
})
gulp.task('default', ['templates'])
It shouldn't be hard to write your own plugin using through2 module (as explained in official docs.)
// gulpfile.js
const gulp = require('gulp');
const path = require('path');
const through = require('through2'); // npm install --save-dev through2
const toTemplateModule = obj => {
return [
`const template = ${JSON.stringify(obj, null, 2)};`,
'',
'export default template;'
].join('\n');
};
const mergeTemplate = file => {
const results = {};
let latestFile;
return through.obj(
function(file, encoding, callback) {
latestFile = file;
results[path.basename(file.path)] = file.contents.toString(encoding);
callback(null, file);
},
function(callback) {
const joinedFile = latestFile.clone({
contents: false
});
joinedFile.path = path.join(latestFile.base, file);
joinedFile.contents = Buffer.from(toTemplateModule(results), 'utf-8');
this.push(joinedFile);
callback();
});
};
gulp.task('templates', () => {
return gulp
.src('./src/templates/**/*.html')
.pipe(mergeTemplate('templates.js'))
.pipe(gulp.dest('./build'))
});
gulp.task('default', ['templates'])
There is a task 'serve' with watch functions as shown below:
gulp.task('serve', function() {
gulp.watch(['source/scripts/*.js'], ['concatjs', reload]);
gulp.watch(['source/styles/*.css'], ['concatcss', reload]);
gulp.watch(['app/static/*.html'], [reload]);
});
When I update js or css files gulp executes only concatjs or concatcss tasks correspondingly. But if to update the html file gulp executes all tasks even the tasks that wasn't registered to the watch function and it throws an error:
[18:26:31] Starting 'lesstocss'...
[18:26:31] Starting 'concatjs'...
[18:26:31] Starting 'concatcss'...
[18:26:31] Starting 'serve'...
[error] You tried to start Browsersync twice! To create multiple instances, use browserSync.create().init()
[18:26:31] Finished 'serve' after 6.1 ms
[18:26:31] Finished 'lesstocss' after 38 ms
[18:26:31] Finished 'concatjs' after 47 ms
[18:26:31] Finished 'concatcss' after 41 ms
Maybe gulp works with the html files in another way? All code I use:
var gulp = require('gulp');
var concat = require('gulp-concat');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var less = require('gulp-less');
var sourcemaps = require('gulp-sourcemaps');
gulp.task('lesstocss', function () {
return gulp.src('source/styles/*.less')
.pipe(sourcemaps.init())
.pipe(less())
.pipe(sourcemaps.write())
.pipe(gulp.dest('source/styles/'));
});
gulp.task('concatjs', function() {
return gulp.src(['source/scripts/mls.js', 'source/scripts/main.js'])
.pipe(concat('result.js'))
.pipe(gulp.dest('app/static/scripts/'));
});
gulp.task('concatcss', function() {
return gulp.src(['source/styles/mls.css', 'source/styles/main.css'])
.pipe(concat('result.css'))
.pipe(gulp.dest('app/static/styles/'));
})
gulp.task('serve', function() {
browserSync.init({
proxy: "localhost:3000",
browser: "google chrome",
notify: false,
open: 'local'
});
gulp.watch(['source/scripts/*.js'], ['concatjs', reload]);
gulp.watch(['source/styles/*.css'], ['concatcss', reload]);
gulp.watch(['app/static/*.html'], [reload]);
});
var gulp = require("gulp");
var changedInPlace = require("gulp-changed-in-place");
var browserSync = require("browser-sync").create();
var sass = require("gulp-sass");
var uglify = require("gulp-uglify");
var concat = require("gulp-concat");
var rename = require("gulp-rename");
var autoprefixer = require("gulp-autoprefixer");
var cleanCSS = require("gulp-clean-css");
// var sourcemaps = require("gulp-sourcemaps");
// var runSequence = require("run-sequence");
// Static Server + watching scss/html files
gulp.task("browsersync", ["sass"], function() {
browserSync.init({
server: {
baseDir: "./",
index: "home.html"
},
ghostMode: false
});
gulp.watch("./scss/*.scss", ["sass"]);
gulp.watch("./*.html").on("change", browserSync.reload);
gulp.watch("./js/*.js").on("change", browserSync.reload);
});
// Compile sass into CSS & auto-inject into browsers
gulp.task("sass", function() {
return gulp.src("./scss/*.scss")
.pipe(changedInPlace())
.pipe(sass().on("error", sass.logError))
.pipe(gulp.dest("./css"))
.pipe(browserSync.stream());
});
At this point I thought it would be instructive to show my working gulpfile.js. It uses sass but you can swap that. Note it uses the preferred
var browserSync = require("browser-sync").create();
and avoids the unusual and possibly problematic arrays you have in your watch statements. But if you really have 2 'serve' tasks defined that is probably your problem (see my comment below)
I am not sure the following line is valid syntax:
gulp.watch(['app/static/*.html'], [reload]);
gulp.watch(glob[, opts], tasks) : when used this way - as you are doing - tasks is an array of STRINGS which themselves are created by gulp.task(). See the docs
Names of task(s) to run when a file changes, added with gulp.task()
from https://github.com/gulpjs/gulp/blob/master/docs/API.md#gulpwatchglob--opts-tasks-or-gulpwatchglob--opts-cb
We definitely need to see reload and the rest of your gulpfile.js
Here is sample code which works with browserSync reload for example:
gulp.watch("./scss/*.scss", ["scss-watch"]);
gulp.watch("./*.html").on("change", browserSync.reload);
// gulp.watch("./css/*.css").on("change", browserSync.reload);
gulp.watch("./js/*.js").on("change", browserSync.reload);
I'm using gulp to watch certain files and run certain tasks however after the first few runs it seems to stop watching. If I save html files in the pages directory, after the first two to five updates, the templates task seems to stop running. I've included my gulpfile below.
// Include gulp
var gulp = require('gulp');
// Include plugins
var jshint = require('gulp-jshint');
var sass = require('gulp-sass');
var notify = require('gulp-notify')
var htmlv = require('gulp-html-validator')
var swig = require('gulp-swig');
var plumber = require('gulp-plumber');
// Linting
gulp.task('lint', function() {
return gulp.src('js/*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
gulp.task('sass', function() {
return gulp.src('./resources/scss/*.scss')
.pipe(sass()
.on('error', notify.onError(function(error) {
return 'Error: ' + error.message;
}))
)
.pipe(gulp.dest('./css'));
});
gulp.task('validate', function() {
return gulp.src('./**.html')
.pipe(htmlv({format: 'xhtml'}))
.pipe(gulp.dest('./validation_out'));
});
gulp.task('watch', function() {
gulp.watch('js/*.js', ['lint']);
gulp.watch('./resources/scss/*.scss', ['sass']);
gulp.watch('./pages/*.html', ['templates']);
});
gulp.task('templates', function() {
return gulp.src('./pages/*.html')
.pipe(swig({
load_json: true,
defaults: {
cache: false
}
}
))
.pipe(gulp.dest('.'));
});
gulp.task('default', ['lint', 'sass', 'templates', 'watch']);
I am writing a gulp script for the first time and I am having hard time being able to uglify my JS files based on gulp-if, I actually do think my code is correct :
var gulp = require('gulp');
var gutil = require('gulp-util');
var gulpif = require('gulp-if');
var concat = require('gulp-concat');
var del = require('del');
var uglify = require('gulp-uglify');
var sourcemaps = require('gulp-sourcemaps');
var minifyCSS = require('gulp-minify-css');
var watch = require("gulp-watch");
var argv = require('yargs').argv;
var paths = {
styles: ['css/maaap.css'],
stylesUfe: ['css/ufe.css'],
scripts: ['js/lang.js', 'js/bootstrap.js', 'js/jquery.js', 'js/leaflet.js', 'js/emm.js', 'js/markercluster.js', 'js/moment.js', 'js/geolocate.js'],
scriptsUfe: ['js/ufe.js', 'js/exif.js', 'js/binaryajax.js', 'js/canvasResize.js']
};
// Not all tasks need to use streams
// A gulpfile is just another node program and you can use all packages available on npm
gulp.task('clean', function(cb) {
console.log(cb);
del(['build'], cb);
});
// Merge all the css files from paths.styles then move it to build/css/style.css
// If you append --ufe you also merge the files from paths.stylesUfe
// If you append --prod your file become build/css/style.min.css and is compressed
gulp.task('styles', ['clean'], function() {
var source = (!argv.ufe) ? paths.styles : paths.styles.concat(paths.stylesUfe);
return gulp.src(source)
.pipe(concat('style.min.css'))
.pipe(gulpif(argv.prod, minifyCSS()))
.pipe(gulp.dest('build/css'));
});
// Merge all the css js files from paths.scripts then move it to build/js/livemap.js
// If you append --ufe you also merge the files from paths.scriptsUfe
// If you append --prof your file become build/js/livemap.min.js and is compressed
gulp.task('scripts', function() {
var source = (!argv.ufe) ? paths.scripts : paths.scripts.concat(paths.scriptsUfe);
return gulp.src(source)
.pipe(concat('livemap.min.js'))
.pipe(gulpif(argv.prod, uglify()))
.pipe(gulp.dest('build/js'))
});
gulp.task('watch', function() {
watch({glob: 'js/**/*.js'}, function (files) {
gulp.start('scripts'); // run the compile task
});
watch({glob: 'css/*.css'}, function (files) {
gulp.start('styles'); // run the compile task
});
});
// The default task (called when you run `gulp` from cli)
gulp.task('default', ['scripts', 'styles']);
The error logs I got in my console are very strange to me :
stream.js:94
throw er; // Unhandled stream error in pipe.
^
Error
at new JS_Parse_Error (/home/soueuls/Projects/MAAAP/node_modules/gulp-uglify/node_modules/uglify-js/lib/parse.js:189:18)
at js_error (/home/soueuls/Projects/MAAAP/node_modules/gulp-uglify/node_modules/uglify-js/lib/parse.js:197:11)
at croak (/home/soueuls/Projects/MAAAP/node_modules/gulp-uglify/node_modules/uglify-js/lib/parse.js:656:9)
at token_error (/home/soueuls/Projects/MAAAP/node_modules/gulp-uglify/node_modules/uglify-js/lib/parse.js:664:9)
at unexpected (/home/soueuls/Projects/MAAAP/node_modules/gulp-uglify/node_modules/uglify-js/lib/parse.js:670:9)
at expr_atom (/home/soueuls/Projects/MAAAP/node_modules/gulp-uglify/node_modules/uglify-js/lib/parse.js:1154:13)
at maybe_unary (/home/soueuls/Projects/MAAAP/node_modules/gulp-uglify/node_modules/uglify-js/lib/parse.js:1327:19)
at expr_op (/home/soueuls/Projects/MAAAP/node_modules/gulp-uglify/node_modules/uglify-js/lib/parse.js:1349:33)
at expr_ops (/home/soueuls/Projects/MAAAP/node_modules/gulp-uglify/node_modules/uglify-js/lib/parse.js:1362:16)
at maybe_conditional (/home/soueuls/Projects/MAAAP/node_modules/gulp-uglify/node_modules/uglify-js/lib/parse.js:1367:20)
at maybe_assign (/home/soueuls/Projects/MAAAP/node_modules/gulp-uglify/node_modules/uglify-js/lib/parse.js:1391:20)
at expression (/home/soueuls/Projects/MAAAP/node_modules/gulp-uglify/node_modules/uglify-js/lib/parse.js:1410:20)
at expr_list (/home/soueuls/Projects/MAAAP/node_modules/gulp-uglify/node_modules/uglify-js/lib/parse.js:1177:24)
Any ideas ?