I have a strange problem, google chrome won't read es6, like let or const or the new way to define a function inside an object.
If i used var it will work fine:
var cat = {
name: 'meow',
age: 5,
eyeColor: 'black'
}
If i used let or const it won't work:
let cat = {
name: 'meow',
age: 5,
eyeColor: 'black'
}
It gives me an error:
cat is not defined
Ok i figured something out, first of all here is my folder structure :
build
assets
js
app.js
vendors.js
source
js
app.js
vendors
gulpfile.js
I am writing all my code inside the source folder and gulp compile it to the build folder, here is my gulp file ( sorry its very long ) :
// --------------------------------------------
// Dependencies
// --------------------------------------------
var autoprefixer = require('gulp-autoprefixer'),
concat = require('gulp-concat'),
del = require('del'),
gulp = require('gulp'),
minifycss = require('gulp-minify-css'),
plumber = require('gulp-plumber'),
sass = require('gulp-sass'),
sourcemaps = require('gulp-sourcemaps'),
rename = require('gulp-rename'),
uglify = require('gulp-uglify'),
images = require('gulp-imagemin'),
browserSync = require('browser-sync').create();
// paths
var styleSrc = 'source/sass/**/*.sass',
styleDest = 'build/assets/css/',
htmlSrc = 'source/',
htmlDest = 'build/',
vendorSrc = 'source/js/vendors/',
vendorDest = 'build/assets/js/',
scriptSrc = 'source/js/*.js',
scriptDest = 'build/assets/js/';
// --------------------------------------------
// Stand Alone Tasks
// --------------------------------------------
// Compiles all SASS files
gulp.task('sass', function() {
gulp.src('source/sass/**/*.sass')
.pipe(plumber())
.pipe(sass({
style: 'compressed'
}))
.pipe(rename({
basename: 'main',
suffix: '.min'
}))
.pipe(gulp.dest('build/assets/css'));
});
gulp.task('images', function() {
gulp.src('source/img/*')
.pipe(images())
.pipe(gulp.dest('build/assets/img'));
});
// Uglify js files
gulp.task('scripts', function() {
gulp.src('source/js/*.js')
.pipe(plumber())
.pipe(uglify())
.pipe(gulp.dest('build/assets/js'));
});
//Concat and Compress Vendor .js files
gulp.task('vendors', function() {
gulp.src(
[
'source/js/vendors/jquery.min.js',
'source/js/vendors/*.js'
])
.pipe(plumber())
.pipe(concat('vendors.js'))
.pipe(uglify())
.pipe(gulp.dest('build/assets/js'));
});
// Watch for changes
gulp.task('watch', function(){
// Serve files from the root of this project
browserSync.init({
server: {
baseDir: "./build"
},
notify: false
});
gulp.watch(styleSrc,['sass']);
gulp.watch(scriptSrc,['scripts']);
gulp.watch(vendorSrc,['vendors']);
gulp.watch(['build/*.html', 'build/assets/css/*.css', 'build/assets/js/*.js', 'build/assets/js/vendors/*.js']).on('change', browserSync.reload);
});
// use default task to launch Browsersync and watch JS files
gulp.task('default', [ 'sass', 'scripts', 'vendors', 'watch'], function () {});
When i write my code inside the build js file directly its working fine, but if i am writing my js inside the source folder it will only compile var, but if i tried let or const it won't
Using let has changed the scope of the variable cat. The error is not being generated at the declaration (bring up the Chrome console and paste your example to prove this to yourself).
The MDN documentation for let says:
The let statement declares a block scope local variable
Compare the given examples. Here's let:
let x = 1;
if (x === 1) {
let x = 2;
console.log(x);
// expected output: 2
}
console.log(x);
// expected output: 1
And here's var:
var x = 1;
if (x === 1) {
var x = 2;
console.log(x);
// expected output: 2
}
console.log(x);
// expected output: 2
Notice the difference in the first and second outputs from each example? In short, the error is actually in code that has not been shared yet. This example highlights the difference:
if (true) {
var myVariable = 1;
let myOtherVariable = 2;
}
console.log(myVariable); //Outputs '1'
console.log(myOtherVariable); //Fails
Alright i fixed it just in case anybody had this problem all you have to do is add babel to the watch task like so :
gulp.task('scripts', function() {
return gulp.src('source/js/*.js')
.pipe(babel({
presets: ['#babel/env']
}))
.pipe(uglify())
.pipe(plumber())
.pipe(gulp.dest('build/assets/js'))
});
Related
I'm trying to use Gulp as part of a React tutorial I'm walking through. After installing the dependencies I've been given;
AssertionError [ERR_ASSERTION]: Task function must be specified
This is the gulpfile.js which I am using
'use strict';
// dependencies
var gulp = require('gulp');
var sass = require('gulp-sass');
var minifyCSS = require('gulp-clean-css');
var uglify = require('gulp-uglify');
var renamed = require('gulp-rename');
var changed = require('gulp-changed');
// - SCSS/CSS
var SCSS_SRC = './src/Assets/scss/**/*.scss';
var SCSS_DEST = './src/Assets/css';
// Compile SCSS
gulp.task('compile_scss', function(){
gulp.src(SCSS_SRC)
.pipe(sass().on('error', sass.logError))
.pipe(minifyCSS())
.pipe(rename({ suffix: '.min' }))
.pipe(changed(SCSS_DEST))
.pipe(gulp.dest(SCSS_DEST));
});
// detect changes in SCSS
gulp.task('watch_scss', function(){
gulp.watch(SCSS_SRC, ['compile_scss']);
});
// Run tasks
gulp.task('default', ['watch_scss']);
And this outputs the following messages
generatedMessage: false,
code: 'ERR_ASSERTION',
actual: false,
expected: true,
operator: '=='
The tutorial I am using was made in April 2017. Could it be something to do with conflicting versions?
Any help is appreciated.
The problem was I was using v3 gulp, the problem was solved by upgrading to v4.
The code is below.
'use strict';
// dependencies
var gulp = require('gulp');
var sass = require('gulp-sass');
var minifyCSS = require('gulp-clean-css');
var uglify = require('gulp-uglify');
var renamed = require('gulp-rename');
var changed = require('gulp-changed');
// - SCSS/CSS
var SCSS_SRC = './src/Assets/scss/**/*.scss';
var SCSS_DEST = './src/Assets/css';
function compile_scss (done) {
gulp.src(SCSS_SRC)
.pipe(sass().on('error', sass.logError))
.pipe(minifyCSS())
.pipe(renamed({ suffix: '.min' }))
.pipe(changed(SCSS_DEST))
.pipe(gulp.dest(SCSS_DEST));
done();
}
// detect changes in SCSS
function detect_change_scss (done) {
gulp.watch(SCSS_SRC)
done();
}
// Run tasks
gulp.task("compile_scss", gulp.series(compile_scss, detect_change_scss, ));
I have a gulp file, and when I run it only the JavaScript files get complied and the less files doesn't get compiled, and I cannot seem to understand why is this happening.
This is my gulp file:
'use strict';
var path = require('path');
var gulp = require('gulp');
var concat = require('gulp-concat');
var sourcemaps = require('gulp-sourcemaps');
var less = require('gulp-less');
var watch = require('gulp-watch');
var jshint = require('gulp-jshint');
var jscs = require('gulp-jscs');
var livereload = require('gulp-livereload');
var jsFiles = ['*.js', 'src/**/*.js'];
// js hints
gulp.task('hints', function(){
return gulp.src(jsFiles)
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish', {
verbose: true
}))
.pipe(jscs()); });
// less
gulp.task('less', function () {
return gulp.src('./public/src/less/main.less')
.pipe(less({ paths: [path.join(__dirname, 'less', 'includes')] }))
.pipe(gulp.dest('./public/src/less/css')); });
// concat
gulp.task('concat', ['concat:css', 'concat:js']); gulp.task('concat:css', function() {
return gulp.src([
'public/lib/bower_components/bootstrap/dist/css/bootstrap.min.css',
'public/lib/bower_components/swiper/dist/css/swiper.min.css',
'public/lib/bower_components/font-awesome/css/font-awesome.min.css',
'public/src/less/css/main.css'
])
.pipe(concat('styles.css'))
.pipe(gulp.dest('./public/build/')); }); gulp.task('concat:js', function() {
return gulp.src([
'public/lib/bower_components/jquery/dist/jquery.min.js',
'public/lib/bower_components/bootstrap/dist/js/bootstrap.min.js',
'public/lib/bower_components/swiper/dist/js/swiper.min.js',
'public/lib/bower_components/jquery.scrollTo/jquery.scrollTo.min.js',
'public/lib/bower_components/jquery.localScroll/jquery.localScroll.min.js',
'public/lib/bower_components/jquery-waypoints/lib/jquery.waypoints.min.js',
'public/lib/bower_components/gsap/src/uncompressed/TweenMax.js',
'public/lib/bower_components/scrollmagic/scrollmagic/uncompressed/ScrollMagic.js',
'public/lib/bower_components/scrollmagic/scrollmagic/uncompressed/plugins/animation.gsap.js',
'public/lib/bower_components/scrollmagic/scrollmagic/uncompressed/plugins/debug.addIndicators.js',
'public/src/js/init.js',
'public/src/js/utils.js',
'public/src/js/main.js'
])
.pipe(concat('scripts.js'))
.pipe(gulp.dest('./public/build/')); });
// watch
gulp.task('watch', ['watch:css', 'watch:js']);
gulp.task('watch:css', function () {
gulp.watch('public/src/less/*.less', ['less', 'concat:css']);
});
gulp.task('watch:js', function () {
gulp.watch('public/src/js/*.js', ['concat:js', 'hints']);
});
gulp.task('build', [ 'less', 'concat']);
gulp.task('development', [ 'less', 'concat', 'watch']);
When I run gulp development the css and js file gets created under the build folder but because the less files dont get compiled to css the css file under build folder has none of my styles.
Does someone know how to solve this issue?
Thank you
Below is a gulp task that has been created to compile angular2 tests written in typescript.
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var debug = require('gulp-debug');
var browserSync = require('browser-sync');
var $ = require('gulp-load-plugins')();
var typescript = require('typescript');
var tsTestProject = $.typescript.createProject({
target: 'es5',
sortOutput: true,
typescript: typescript,
experimentalDecorators: true
});
gulp.task('scripts-test', [], function () {
var gulpStream = gulp.src([
path.join(conf.paths.src, '/app/references.test.ts'),
path.join(conf.paths.src, '/app/**/*.spec.ts')
])
.pipe(debug())
.pipe($.sourcemaps.init())
.pipe($.typescript(tsTestProject)).on('error', conf.errorHandler('TypeScript'))
.pipe($.sourcemaps.write())
.pipe(gulp.dest('tmptest'))
.pipe(browserSync.reload({ stream: true }))
.pipe($.size());
return gulpStream;
});
Here's the log related to the task.
[20:47:45] Starting 'scripts-test'...
[20:50:18] TypeScript: emit succeeded (with errors)
[20:50:18] Finished 'scripts-test' after 2.53 min
Yet no output files (typescripts compiled into js) are created to a tmptest folder as given in the task. gulp-debug shows that all the files given in gulp.src are acquired to the stream. Any idea as to why this is happening?
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.
I am using Gulp as my task runner and browserify to bundle my CommonJs modules.
I have noticed that running my browserify task is quite slow, it takes around 2 - 3 seconds, and all I have is React and a few very small components I have built for development.
Is there a way to speed up the task, or do I have any noticeable problems in my task?
gulp.task('browserify', function() {
var bundler = browserify({
entries: ['./main.js'], // Only need initial file
transform: [reactify], // Convert JSX to javascript
debug: true, cache: {}, packageCache: {}, fullPaths: true
});
var watcher = watchify(bundler);
return watcher
.on('update', function () { // On update When any files updates
var updateStart = Date.now();
watcher.bundle()
.pipe(source('bundle.js'))
.pipe(gulp.dest('./'));
console.log('Updated ', (Date.now() - updateStart) + 'ms');
})
.bundle() // Create initial bundle when starting the task
.pipe(source('bundle.js'))
.pipe(gulp.dest('./'));
});
I am using Browserify, Watchify, Reactify and Vinyl Source Stream as well as a few other unrelated modules.
var browserify = require('browserify'),
watchify = require('watchify'),
reactify = require('reactify'),
source = require('vinyl-source-stream');
Thanks
See fast browserify builds with watchify. Note that the only thing passed to browserify is the main entry point, and watchify's config.
The transforms are added to the watchify wrapper.
code from article pasted verbatim
var gulp = require('gulp');
var gutil = require('gulp-util');
var sourcemaps = require('gulp-sourcemaps');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var watchify = require('watchify');
var browserify = require('browserify');
var bundler = watchify(browserify('./src/index.js', watchify.args));
// add any other browserify options or transforms here
bundler.transform('brfs');
gulp.task('js', bundle); // so you can run `gulp js` to build the file
bundler.on('update', bundle); // on any dep update, runs the bundler
function bundle() {
return bundler.bundle()
// log errors if they happen
.on('error', gutil.log.bind(gutil, 'Browserify Error'))
.pipe(source('bundle.js'))
// optional, remove if you dont want sourcemaps
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: true})) // loads map from browserify file
.pipe(sourcemaps.write('./')) // writes .map file
//
.pipe(gulp.dest('./dist'));
}
You have to use watchify and enable its cache. Take a look at :
https://www.codementor.io/reactjs/tutorial/react-js-browserify-workflow-part-2
and for more optimisation when building source-map you could do that :
cd node_modules/browserify && npm i substack/browser-pack#sm-fast
this would safe you half of time
part of my gulpfile.js
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var htmlreplace = require('gulp-html-replace');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var watchify = require('watchify');
var reactify = require('reactify');
var streamify = require('gulp-streamify');
var path = {
OUT : 'build.js',
DEST2 : '/home/apache/www-modules/admimail/se/se',
DEST_BUILD : 'build',
DEST_DEV : 'dev',
ENTRY_POINT : './src/js/main.jsx'
};
gulp.task('watch', [], function() {
var bundler = browserify({
entries : [ path.ENTRY_POINT ],
extensions : [ ".js", ".jsx" ],
transform : [ 'reactify' ],
debug : true,
fullPaths : true,
cache : {}, // <---- here is important things for optimization
packageCache : {} // <---- and here
});
bundler.plugin(watchify, {
// delay: 100,
// ignoreWatch: ['**/node_modules/**'],
// poll: false
});
var rebundle = function() {
var startDate = new Date();
console.log('Update start at ' + startDate.toLocaleString());
return bundler.bundle(function(err, buf){
if (err){
console.log(err.toString());
} else {
console.log(' updated in '+(new Date().getTime() - startDate.getTime())+' ms');
}
})
.pipe(source(path.OUT))
.pipe(gulp.dest(path.DEST2 + '/' + path.DEST_DEV))
;
};
bundler.on('update', rebundle);
return rebundle();
});
gulp.task('default', [ 'watch' ]);
Many thanks to #PHaroZ for that answer. I had to modify a little bit that code for my needs though. I am working with ReactJS on Symfony2 framework and all my builds were taking 7s-21s!!! Crazy.. So that's what I have now:
var path = {
OUT : 'app.js',
DEST_BUILD : './src/MyBundle/Resources/js/dist',
ENTRY_POINT : './src/MyBundle/Resources/js/src/app.js'
};
gulp.task('watch', [], function() {
var bundler = browserify({
entries : [ path.ENTRY_POINT ],
extensions : [ ".js", ".jsx" ],
// transform : [ 'reactify' ],
debug : true,
fullPaths : true,
cache : {}, // <---- here is important things for optimization
packageCache : {} // <---- and here
}).transform("babelify", {presets: ["es2015", "react"]});
bundler.plugin(watchify, {
// delay: 100,
// ignoreWatch: ['**/node_modules/**'],
// poll: false
});
var rebundle = function() {
var startDate = new Date();
console.log('Update start at ' + startDate.toLocaleString());
return bundler.bundle(function(err, buf){
if (err){
console.log(err.toString());
} else {
console.log(' updated in '+(new Date().getTime() - startDate.getTime())+' ms');
}
})
.pipe(source(path.OUT))
.pipe(gulp.dest(path.DEST_BUILD))
;
};
bundler.on('update', rebundle);
return rebundle();
});
Now first compile takes around 20s and each time I update my file it takes around 800ms. It's just enough time to switch from IDE to my browser.